#!/usr/bin/env python3
"""Generate PUBLIC_API.json from the live __all__ of every public module (DOC-08/REL-03).

PUBLIC_API.md is the human contract; this JSON is the machine companion. Pinned by
tests/unit/test_public_api_json_pin.py — regenerating MUST reproduce the checked-in file.
Usage:  python tools/generate_public_api_json.py
"""

from __future__ import annotations

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

PUBLIC_MODULES = (
    "mgf.test_supervisor.records",
    "mgf.test_supervisor.tiers",
    "mgf.test_supervisor.selection",
    "mgf.test_supervisor.quarantine",
    "mgf.test_supervisor.perf",
    "mgf.test_supervisor.supervisor",
    "mgf.test_supervisor.diagnostics",
    "mgf.test_supervisor.self_check",
)


def build_payload() -> dict[str, Any]:
    modules: dict[str, list[str]] = {}
    total = 0
    for name in PUBLIC_MODULES:
        mod = importlib.import_module(name)
        names = sorted(getattr(mod, "__all__", []))
        modules[name] = names
        total += len(names)
    version = importlib.import_module("mgf.test_supervisor").__version__
    return {
        "__version__": version,
        "modules": modules,
        "__generated_at_module_count": len(PUBLIC_MODULES),
        "__generated_total_names": total,
    }


def write_json(path: Path) -> None:
    path.write_text(json.dumps(build_payload(), indent=2, sort_keys=True) + "\n", encoding="utf-8")


if __name__ == "__main__":
    out = Path(__file__).resolve().parent.parent / "PUBLIC_API.json"
    write_json(out)
    print(f"wrote {out}")
