#!/usr/bin/env python3
"""Fail when a literal Go ServeMux route is absent from the OpenAPI contract."""
from __future__ import annotations
import re
from pathlib import Path
import yaml

ROUTE = re.compile(r'HandleFunc\("(GET|POST|PUT|PATCH|DELETE) ([^" ]+)"')
PARAM = re.compile(r"\{[^{}]+\}")


def normalized(method: str, path: str) -> tuple[str, str]:
    return method.upper(), PARAM.sub("{}", path)


document = yaml.safe_load(Path("api/openapi/gateway.yaml").read_text())
contract = {normalized(method, path) for path, value in document["paths"].items() for method in value if method.lower() in {"get", "post", "put", "patch", "delete"}}
implemented = set()
for source in list(Path("internal").rglob("*.go")) + list(Path("cmd").rglob("*.go")):
    for method, path in ROUTE.findall(source.read_text()):
        implemented.add((normalized(method, path), str(source)))
missing = sorted((route, source) for route, source in implemented if route not in contract)
for (method, path), source in missing:
    print(f"{method} {path} ({source})")
if missing:
    raise SystemExit(f"{len(missing)} implemented literal routes are missing from OpenAPI")
print(f"OpenAPI covers {len(implemented)} literal Go routes")
