"""Generate `docs/tools.md` — a Markdown catalogue of every registered tool.

The MCP has 100+ tools. Onboarding (human or agent) used to require
reading the source. This script generates a single doc with one row
per tool: name, BASIC/INTERMEDIATE/EXPERT tier, description,
input schema summary. Re-run after every tool change; CI validates
it matches the live registry.

Usage:
    python -m scripts.generate_tool_catalogue              # write to docs/
    python -m scripts.generate_tool_catalogue --check      # CI mode: fail if stale
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path


def _generate(env_quiet: bool = True) -> str:
    if env_quiet:
        import os

        os.environ.setdefault("MCP_QUIET", "1")
    from mcp_phone_controll.container import build_runtime
    from mcp_phone_controll.domain.tool_levels import BASIC_TOOLS, INTERMEDIATE_TOOLS

    _, dispatcher = build_runtime()
    by_name = sorted(dispatcher.descriptors, key=lambda d: d.name)

    def tier_for(name: str) -> str:
        if name in BASIC_TOOLS:
            return "BASIC"
        if name in INTERMEDIATE_TOOLS:
            return "INTERMEDIATE"
        return "expert"

    lines = [
        "# Tool catalogue — flutter-dev-agents / phone-controll",
        "",
        "_Auto-generated by `scripts/generate_tool_catalogue.py`. Don't edit "
        "by hand; re-run after tool changes._",
        "",
        f"**Total tools registered:** {len(by_name)}.",
        "",
        "Tiers:",
        "- **BASIC** — visible at `describe_capabilities(level=\"basic\")` "
        "(~18 tools). What a 4B agent sees.",
        "- **INTERMEDIATE** — adds dev-loop, code-quality, multi-window, "
        "AR/Vision essentials.",
        "- **expert** — everything else (visible by default).",
        "",
        "## Tools",
        "",
        "| Tool | Tier | Description |",
        "|---|---|---|",
    ]
    for d in by_name:
        desc = d.description.replace("\n", " ").replace("|", "\\|")
        lines.append(f"| `{d.name}` | {tier_for(d.name)} | {desc} |")
    lines.append("")
    lines.append("## Input schemas")
    lines.append("")
    for d in by_name:
        props = (d.input_schema or {}).get("properties") or {}
        required = (d.input_schema or {}).get("required") or []
        if not props:
            continue
        lines.append(f"### `{d.name}`")
        lines.append("")
        for prop_name, prop_schema in props.items():
            req_marker = " *(required)*" if prop_name in required else ""
            ptype = (prop_schema or {}).get("type", "any")
            pdesc = (prop_schema or {}).get("description", "")
            row = f"- `{prop_name}: {ptype}`{req_marker} — {pdesc}"
            if row.endswith(" — "):
                row = row[: -len(" — ")]
            lines.append(row)
        lines.append("")
    return "\n".join(lines) + "\n"


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument(
        "--check", action="store_true",
        help="CI mode: fail if generated content doesn't match docs/tools.md",
    )
    ap.add_argument(
        "--output", type=Path,
        default=Path(__file__).resolve().parents[3] / "docs" / "tools.md",
        help="Destination Markdown file.",
    )
    args = ap.parse_args()

    content = _generate()
    if args.check:
        existing = args.output.read_text() if args.output.is_file() else ""
        if existing.strip() != content.strip():
            print(
                "docs/tools.md is stale. Re-run "
                "`python -m scripts.generate_tool_catalogue`.",
                file=sys.stderr,
            )
            return 1
        print("tool catalogue is current.")
        return 0
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(content)
    print(f"wrote {args.output}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
