from pathlib import Path

import pytest

from ki2_externai import registry


@pytest.fixture(autouse=True)
def _patch_registry_dir(tmp_path, monkeypatch):
    """Redirect the platform data dir to a temporary folder for isolation."""
    monkeypatch.setattr(registry, "user_data_dir", lambda app, author: str(tmp_path / "data"))
    return tmp_path / "data"


def test_save_and_load_registry(tmp_path):
    """Save a simple entry and make sure it is read back untouched."""
    data = {"libA": "/tmp/libA"}
    registry.save_registry(data)

    assert registry.load_registry() == data


def test_find_names_for_path(tmp_path):
    """Finding names should only return the entries that point to the requested folder."""
    data = {"libA": str(tmp_path / "libA"), "toolkit": "/tmp/toolkit"}
    registry.save_registry(data)

    names = registry.find_names_for_path(tmp_path / "libA")
    assert names == ["libA"]


def test_no_registry_file(tmp_path):
    """Loading when the file is missing should return an empty dict."""
    assert registry.load_registry() == {}


def test_resolution_after_write(tmp_path):
    """After saving an entry, it should resolve via its name."""
    data = {"project": str(tmp_path / "data")}
    registry.save_registry(data)

    assert registry.resolve_registered_path("project") == data["project"]


def test_duplicate_path_includes_multiple_names(tmp_path):
    """The same path may appear under multiple aliases."""
    data = {"libA": str(tmp_path / "common"), "libB": str(tmp_path / "common")}
    registry.save_registry(data)

    names = registry.find_names_for_path(tmp_path / "common")
    assert sorted(names) == ["libA", "libB"]


def test_loading_invalid_type_errors(tmp_path):
    """If the registry file contains a non-object, we raise."""
    path = registry._registry_file()
    path.write_text("[]")

    with pytest.raises(SystemExit):
        registry.load_registry()
