"""Pin the public-API contract (AP-10 / AP-11 / DOC-08).

Two promises existed only as prose before this file: the generator's docstring
said "Pinned by CI: regenerating MUST reproduce the checked-in file", and AP-10
requires `PUBLIC_API.md` to stay in sync with `__all__`. Nothing checked either.
A documented guarantee nobody verifies is exactly the drift this library exists to
catch elsewhere — so it gets checked here.
"""

from __future__ import annotations

import importlib.util
import json
import re
from pathlib import Path
from typing import Any

import mgf.uitest_web as pkg

_ROOT = Path(__file__).resolve().parents[2]
_JSON = _ROOT / "PUBLIC_API.json"
_MD = _ROOT / "PUBLIC_API.md"
_GENERATOR = _ROOT / "tools" / "generate_public_api_json.py"

#: The tiers AP-11 allows — no others.
_TIERS = frozenset({"experimental", "stable", "deprecated"})

#: A §2 row: | `Name` | kind | `tier` | description |
_ROW = re.compile(r"\|\s*`([^`]+)`\s*\|[^|]*\|\s*`([^`]+)`\s*\|")


def _md_rows() -> list[tuple[str, str]]:
    """(name, tier) per row of PUBLIC_API.md §2's importable-surface table."""
    text = _MD.read_text(encoding="utf-8")
    section = text.split("## §2.")[1].split("## §3.")[0]
    return [(m.group(1), m.group(2)) for line in section.splitlines() if (m := _ROW.match(line))]


def _load_generator() -> Any:
    spec = importlib.util.spec_from_file_location("_gen_public_api", _GENERATOR)
    assert spec is not None and spec.loader is not None
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def test_public_api_json_is_reproducible() -> None:
    generator = _load_generator()
    expected = json.dumps(generator.build_payload(), indent=2, sort_keys=True) + "\n"
    assert _JSON.read_text(encoding="utf-8") == expected, (
        "PUBLIC_API.json is stale — run: python tools/generate_public_api_json.py"
    )


def test_public_api_md_lists_exactly_dunder_all() -> None:
    documented = {name for name, _ in _md_rows()}
    declared = set(pkg.__all__)
    assert documented == declared, (
        f"PUBLIC_API.md §2 is out of sync with __all__ (AP-10). "
        f"missing from the doc={sorted(declared - documented)}; "
        f"documented but not exported={sorted(documented - declared)}"
    )


def test_every_public_name_declares_a_valid_tier() -> None:
    rows = _md_rows()
    assert rows, "PUBLIC_API.md §2 parsed to zero rows — the table shape changed"
    bad = {name: tier for name, tier in rows if tier not in _TIERS}
    assert not bad, f"invalid stability tier(s); AP-11 allows {sorted(_TIERS)}: {bad}"


def test_json_and_md_describe_the_same_surface() -> None:
    payload = json.loads(_JSON.read_text(encoding="utf-8"))
    assert set(payload["modules"]["mgf.uitest_web"]) == {n for n, _ in _md_rows()}
    assert payload["__version__"] == pkg.__version__
