"""Tests para unregister_obsidian_vault."""

import json

from unregister_obsidian_vault import unregister_obsidian_vault


def _write_cfg(cfg):
    with open(cfg, "w", encoding="utf-8") as f:
        json.dump(
            {
                "extra": "preservar",
                "appVersionLastUsed": "1.5.3",
                "vaults": {
                    "aaaaaaaaaaaaaaaa": {"path": "/a/Alpha", "ts": 100, "open": True},
                    "bbbbbbbbbbbbbbbb": {"path": "/b/Beta", "ts": 200, "open": False},
                },
            },
            f,
        )


def _read(cfg):
    with open(cfg, "r", encoding="utf-8") as f:
        return json.load(f)


def test_desregistra_por_path(tmp_path):
    # Golden path: quita la entrada cuya 'path' coincide con la ruta dada.
    cfg = str(tmp_path / "obsidian.json")
    _write_cfg(cfg)

    res = unregister_obsidian_vault("/a/Alpha", config_path=cfg)
    assert res["removed"] is True
    assert res["id"] == "aaaaaaaaaaaaaaaa"
    assert res["path"] == "/a/Alpha"
    assert res["backup_path"] == cfg + ".bak"

    data = _read(cfg)
    assert "aaaaaaaaaaaaaaaa" not in data["vaults"]
    assert "bbbbbbbbbbbbbbbb" in data["vaults"]


def test_desregistra_por_id(tmp_path):
    # Edge: quita la entrada por su id hex exacto.
    cfg = str(tmp_path / "obsidian.json")
    _write_cfg(cfg)

    res = unregister_obsidian_vault("bbbbbbbbbbbbbbbb", config_path=cfg)
    assert res["removed"] is True
    assert res["id"] == "bbbbbbbbbbbbbbbb"
    assert res["path"] == "/b/Beta"

    data = _read(cfg)
    assert "bbbbbbbbbbbbbbbb" not in data["vaults"]


def test_preserva_resto_del_json_al_quitar_entrada(tmp_path):
    # Edge: las demas claves y vaults sobreviven al desregistro.
    cfg = str(tmp_path / "obsidian.json")
    _write_cfg(cfg)

    unregister_obsidian_vault("/a/Alpha", config_path=cfg)

    data = _read(cfg)
    assert data["extra"] == "preservar"
    assert data["appVersionLastUsed"] == "1.5.3"
    assert "bbbbbbbbbbbbbbbb" in data["vaults"]
    assert len(data["vaults"]) == 1


def test_ref_inexistente_devuelve_removed_false(tmp_path):
    # Error path: ni id ni path coinciden -> removed False, sin reescritura.
    cfg = str(tmp_path / "obsidian.json")
    _write_cfg(cfg)

    res = unregister_obsidian_vault("/no/existe", config_path=cfg)
    assert res["removed"] is False
    assert res["id"] == ""
    assert res["backup_path"] == ""

    data = _read(cfg)
    assert len(data["vaults"]) == 2
