"""Tests para create_obsidian_note."""

import os

import pytest

from create_obsidian_note import create_obsidian_note
from read_obsidian_note import read_obsidian_note


def test_crea_nota_con_frontmatter_y_body(tmp_path):
    # Golden path: crea nota con frontmatter + body y crea el subdir padre.
    vault = str(tmp_path)
    path = create_obsidian_note(
        vault,
        "Proyectos/Idea.md",
        body="Primer apunte. [[Proyecto X]].",
        frontmatter={"title": "Idea", "tags": ["inbox"]},
    )
    assert os.path.isfile(path)
    assert path.endswith("Proyectos/Idea.md")

    note = read_obsidian_note(path)
    assert note["frontmatter"]["title"] == "Idea"
    assert note["tags"] == ["inbox"]
    assert "Primer apunte" in note["body"]
    assert note["wikilinks"] == ["Proyecto X"]


def test_anade_extension_md_si_falta(tmp_path):
    # Edge: rel_path sin extension -> se le anade .md.
    path = create_obsidian_note(str(tmp_path), "Inbox/Nota rapida", body="x")
    assert path.endswith("Nota rapida.md")
    assert os.path.isfile(path)


def test_crea_directorios_padre(tmp_path):
    # Edge: crea toda la jerarquia de carpetas que no existe.
    path = create_obsidian_note(str(tmp_path), "a/b/c/Honda.md", body="y")
    assert os.path.isfile(path)
    assert os.path.isdir(os.path.join(str(tmp_path), "a", "b", "c"))


def test_existente_sin_overwrite_lanza_fileexistserror(tmp_path):
    # Error path: la nota ya existe y overwrite=False (default).
    create_obsidian_note(str(tmp_path), "Dup.md", body="original")
    with pytest.raises(FileExistsError):
        create_obsidian_note(str(tmp_path), "Dup.md", body="nuevo")


def test_overwrite_true_sobreescribe(tmp_path):
    # Edge: overwrite=True reemplaza el contenido y devuelve la misma ruta.
    p1 = create_obsidian_note(str(tmp_path), "Dup.md", body="original")
    p2 = create_obsidian_note(
        str(tmp_path), "Dup.md", body="reemplazado", overwrite=True
    )
    assert p1 == p2
    note = read_obsidian_note(p2)
    assert note["body"].strip() == "reemplazado"


def test_destino_directorio_lanza_isadirectoryerror(tmp_path):
    # Error path: el destino resuelto ya es un directorio.
    target = tmp_path / "EsCarpeta.md"
    target.mkdir()
    with pytest.raises(IsADirectoryError):
        create_obsidian_note(str(tmp_path), "EsCarpeta.md", body="x")
