"""Tests para update_obsidian_note."""

import pytest

from read_obsidian_note import read_obsidian_note
from update_obsidian_note import update_obsidian_note


def _seed(tmp_path, name="Nota.md", content="---\ntitle: A\nstatus: open\n---\n\nLinea original."):
    path = tmp_path / name
    path.write_text(content, encoding="utf-8")
    return str(path)


def test_merge_frontmatter_conserva_claves_previas(tmp_path):
    # Golden path: set_frontmatter mergea sin perder claves no mencionadas.
    note = _seed(tmp_path)
    ret = update_obsidian_note(
        note, set_frontmatter={"status": "done", "closed": "2026-06-09"}
    )
    assert ret == note

    fm = read_obsidian_note(note)["frontmatter"]
    assert fm["title"] == "A"            # clave previa conservada
    assert fm["status"] == "done"        # clave existente sobreescrita
    assert fm["closed"] == "2026-06-09"  # clave nueva anadida


def test_reemplazo_de_body(tmp_path):
    # Edge: body no None reemplaza por completo el cuerpo.
    note = _seed(tmp_path)
    update_obsidian_note(note, body="Cuerpo nuevo entero.")
    parsed = read_obsidian_note(note)
    assert parsed["body"].strip() == "Cuerpo nuevo entero."
    assert "Linea original" not in parsed["body"]
    # El frontmatter se conserva intacto.
    assert parsed["frontmatter"]["title"] == "A"


def test_append_concatena_al_final(tmp_path):
    # Edge: append concatena tras el body existente con salto de linea.
    note = _seed(tmp_path)
    update_obsidian_note(note, append="Linea anadida.")
    body = read_obsidian_note(note)["body"]
    assert "Linea original." in body
    assert "Linea anadida." in body
    assert body.index("Linea original.") < body.index("Linea anadida.")


def test_body_y_append_combinados(tmp_path):
    # Edge: append se aplica DESPUES del reemplazo de body.
    note = _seed(tmp_path)
    update_obsidian_note(note, body="Base.", append="Extra.")
    body = read_obsidian_note(note)["body"]
    assert "Base." in body
    assert "Extra." in body
    assert "Linea original" not in body
    assert body.index("Base.") < body.index("Extra.")


def test_nota_inexistente_lanza_filenotfounderror(tmp_path):
    # Error path: actualizar una nota que no existe no la crea.
    with pytest.raises(FileNotFoundError):
        update_obsidian_note(str(tmp_path / "no_existe.md"), body="x")


def test_directorio_lanza_isadirectoryerror(tmp_path):
    # Error path: ruta a directorio.
    sub = tmp_path / "carpeta"
    sub.mkdir()
    with pytest.raises(IsADirectoryError):
        update_obsidian_note(str(sub), body="x")
