"""Registry loader — path resolution, multi-file union, selection helpers."""

from __future__ import annotations

import pytest

from mgf.secrets.registry import (
    Registry,
    RegistryError,
    default_paths,
    fed_root,
    load,
)

ENTRY = """\
[{id}]
family = "{family}"
kind = "api-token"
purpose = "p"
consumers = ["c"]
recovery = "r"
state = "{state}"
policy = {{ allowed_repos = "*", blast_radius = "b" }}
rotation = {{ class = "token", staged = true }}
verify = {{ probe = "auth" }}
surfaces = [ {{ type = "woodpecker-org-secret", events = ["push"] }} ]
"""


def test_fed_root_env_override(monkeypatch, tmp_path) -> None:
    monkeypatch.setenv("MGF_ROOT", str(tmp_path))
    assert fed_root() == tmp_path
    monkeypatch.delenv("MGF_ROOT")
    assert fed_root() == __import__("pathlib").Path.home() / "PycharmProjects"


def test_default_paths_point_at_both_standards(tmp_path) -> None:
    paths = default_paths(tmp_path)
    assert paths[0] == tmp_path / "mgf-standard" / "SECRETS.toml"
    assert paths[1] == tmp_path / "sooth-standard" / "SECRETS.toml"


def test_missing_default_files_raise(tmp_path) -> None:
    with pytest.raises(RegistryError, match=r"no SECRETS\.toml"):
        load(root=tmp_path)


def test_two_files_union_and_select(tmp_path) -> None:
    a = tmp_path / "a.toml"
    b = tmp_path / "b.toml"
    a.write_text(ENTRY.format(id="mgf_one", family="mgf", state="active"), encoding="utf-8")
    b.write_text(ENTRY.format(id="sooth_one", family="sooth", state="held"), encoding="utf-8")
    reg = load([a, b])
    assert isinstance(reg, Registry)
    assert len(reg) == 2
    assert [e.id for e in reg.select(family="mgf")] == ["mgf_one"]
    assert [e.id for e in reg.select(state="held")] == ["sooth_one"]
    assert reg.get("missing") is None


def test_with_surface_helper(tmp_path) -> None:
    a = tmp_path / "a.toml"
    a.write_text(ENTRY.format(id="x", family="mgf", state="active"), encoding="utf-8")
    reg = load([a])
    assert [e.id for e in reg.with_surface("woodpecker-org-secret")] == ["x"]
    assert reg.with_surface("host-file") == []


def test_non_table_entry_fails_closed(tmp_path) -> None:
    a = tmp_path / "a.toml"
    a.write_text('x = "not a table"\n', encoding="utf-8")
    with pytest.raises(RegistryError, match="not a table"):
        load([a])
