#!/usr/bin/env python3
"""Cross-check Swift prefs panes, HTTP route modules, and smoke allowlists."""
from __future__ import annotations

import ast
import re
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
PREFS_DIR = ROOT / "MugiApp" / "Mugi" / "Preferences"
SMOKE_PREFS = ROOT / "tests" / "smoke" / "test_preferences_routes_register.py"
MUGI_BACKEND = ROOT / "mugi_backend.py"


def prefs_panes() -> list[str]:
    return sorted(p.name.replace("PrefsPane.swift", "") for p in PREFS_DIR.glob("*PrefsPane.swift"))


def swift_only_allowlist() -> set[str]:
    text = SMOKE_PREFS.read_text(encoding="utf-8")
    m = re.search(r"SWIFT_ONLY_PANES\s*=\s*frozenset\(\{([^}]+)\}", text, re.DOTALL)
    if not m:
        return set()
    inner = m.group(1)
    return {x.strip().strip("'\"") for x in inner.split(",") if x.strip()}


def registered_http_modules() -> list[str]:
    text = MUGI_BACKEND.read_text(encoding="utf-8")
    return re.findall(r"from\s+(\w+)\s+import\s+register_\w+_http_routes", text)


def route_prefixes_from_module(module: str) -> list[str]:
    path = ROOT / f"{module}.py"
    if not path.is_file():
        return []
    text = path.read_text(encoding="utf-8", errors="replace")
    return sorted(set(re.findall(r'@(?:app|router)\.(?:get|post|put|delete|patch)\(\s*["\']([^"\']+)', text)))


def main() -> int:
    panes = prefs_panes()
    allow = swift_only_allowlist()
    modules = registered_http_modules()

    print("# bridge_route_inventory\n")
    print("## Swift Preferences panes\n")
    for name in panes:
        swift_only = "yes" if name in allow else "no"
        print(f"- {name}PrefsPane (swift-only allowlist: {swift_only})")

    print("\n## HTTP route modules registered from mugi_backend._build_app\n")
    for mod in modules:
        prefixes = route_prefixes_from_module(mod)
        sample = ", ".join(prefixes[:8])
        if len(prefixes) > 8:
            sample += f", … (+{len(prefixes) - 8})"
        print(f"- `{mod}` ({len(prefixes)} routes): {sample or '(parse failed)'}")

    print("\n## Pane → expected route token (heuristic)\n")
    for name in panes:
        token = name.lower()
        if name in allow:
            print(f"- {name}: Swift-only (no backend route required)")
        elif token == "knowledge":
            print(f"- {name}: /knowledge/* via knowledge_http_routes")
        elif token == "diagnostics":
            print(f"- {name}: /doctor or diagnostics endpoints")
        else:
            print(f"- {name}: /preferences/{token}* or satellite routes")

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
