"""PUBLIC_API.json must stay in sync with the live ``mgf.cloud.__all__`` (AP-13/DOC-08)."""

from __future__ import annotations

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

_REPO_ROOT = Path(__file__).resolve().parents[2]


def _load_generator() -> Any:
    path = _REPO_ROOT / "tools" / "generate_public_api_json.py"
    spec = importlib.util.spec_from_file_location("genapi", path)
    assert spec is not None
    assert spec.loader is not None
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def test_public_api_json_matches_all() -> None:
    generator = _load_generator()
    on_disk = json.loads((_REPO_ROOT / "PUBLIC_API.json").read_text(encoding="utf-8"))
    assert on_disk == generator.build_payload(), (
        "PUBLIC_API.json is stale — run `python tools/generate_public_api_json.py`"
    )


def test_public_api_md_mentions_every_name() -> None:
    """RA-10 second pin (AP-10/DOC-08): the human-readable PUBLIC_API.md must
    document every name in __all__ / PUBLIC_API.json — no silent omissions."""
    import mgf.cloud

    md = (_REPO_ROOT / "PUBLIC_API.md").read_text(encoding="utf-8")
    missing = [name for name in mgf.cloud.__all__ if f"`{name}`" not in md]
    assert not missing, f"PUBLIC_API.md is missing rows for: {missing}"


def test_public_api_md_and_json_agree() -> None:
    """The md table and the json companion enumerate the SAME surface."""
    md = (_REPO_ROOT / "PUBLIC_API.md").read_text(encoding="utf-8")
    on_disk = json.loads((_REPO_ROOT / "PUBLIC_API.json").read_text(encoding="utf-8"))
    missing = [name for name in on_disk["modules"]["mgf.cloud"] if f"`{name}`" not in md]
    assert not missing, f"PUBLIC_API.md is out of sync with PUBLIC_API.json: {missing}"
