"""Generiert references/endpoint-catalog.md aus references/openapi.json."""
import json
from pathlib import Path

REF = Path(__file__).parent.parent / "references"
SPEC = json.load(open(REF / "openapi.json", encoding="utf-8"))

groups: dict = {}
for path, item in SPEC["paths"].items():
    for method, op in item.items():
        if method not in ("get", "post", "put", "delete", "patch"):
            continue
        tag = (op.get("tags") or ["(no tag)"])[0]
        groups.setdefault(tag, []).append({
            "operationId": op.get("operationId", ""),
            "method": method.upper(),
            "path": path,
            "summary": op.get("summary", "").strip(),
        })

total_ops = sum(len(g) for g in groups.values())
lines = ["# GetMyInvoices API — Endpoint Catalog", "",
         f"Generiert aus `references/openapi.json`. {total_ops} Operationen in {len(groups)} Gruppen.", ""]
for tag in sorted(groups):
    lines.append(f"## {tag}")
    lines.append("")
    lines.append("| operationId | Method | Path | Summary |")
    lines.append("|---|---|---|---|")
    for op in sorted(groups[tag], key=lambda o: o["operationId"]):
        summary = op["summary"].replace("|", "\\|")
        lines.append(f"| `{op['operationId']}` | {op['method']} | `{op['path']}` | {summary} |")
    lines.append("")

(REF / "endpoint-catalog.md").write_text("\n".join(lines), encoding="utf-8")
print(f"Catalog written: {sum(len(g) for g in groups.values())} operations in {len(groups)} groups")
