#!/usr/bin/env python3
"""Generate ``PUBLIC_API.json`` from the live ``__all__`` of every public module.

The machine-readable public-API companion (DOC-08 / REL-03). Pinned by CI:
regenerating MUST reproduce the checked-in file, else CI fails.

Usage::  python tools/generate_public_api_json.py
"""

from __future__ import annotations

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

#: The public surface — everything is re-exported from the package root's __all__.
PUBLIC_MODULES = ("mgf.uitest_web",)


def build_payload() -> dict[str, Any]:
    modules: dict[str, list[str]] = {}
    total = 0
    for mod_name in PUBLIC_MODULES:
        mod = importlib.import_module(mod_name)
        names = sorted(n for n in getattr(mod, "__all__", []) if n != "__version__")
        modules[mod_name] = names
        total += len(names)
    version = importlib.import_module("mgf.uitest_web").__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}")
