#!/usr/bin/env python3
"""Regenerate src/services/backendRoutes.txt from the backend OpenAPI document.

    curl -s "$API/openapi.yaml" > /tmp/openapi.yaml
    python3 scripts/gen-backend-routes.py /tmp/openapi.yaml > src/services/backendRoutes.txt

Needs PyYAML. The output is one "METHOD /path" per line, sorted, so a
regenerated file diffs cleanly against the committed one and shows exactly
which routes the backend added or dropped.
"""
import sys

import yaml

VERBS = ("get", "post", "put", "patch", "delete")


def main(argv):
    if len(argv) != 2:
        sys.exit(f"usage: {argv[0]} <openapi.yaml>")
    with open(argv[1], encoding="utf-8") as fh:
        spec = yaml.safe_load(fh)

    rows = set()
    for path, ops in (spec.get("paths") or {}).items():
        if not isinstance(ops, dict):
            continue
        for verb in ops:
            if verb.lower() in VERBS:
                rows.add(f"{verb.lower()} {path}")

    if not rows:
        sys.exit("no routes found - refusing to write an empty list")
    sys.stdout.write("\n".join(sorted(rows)) + "\n")


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