#!/usr/bin/env python3
"""Refresh clients/openapi.json from the live app — the snapshot hexa + the
generated clients build against (#32, #44).

`app.app.openapi()` omits the public `servers` block (it's only injected when
served behind the gateway's root_path), so we add it here. test_openapi_snapshot
guards both the path set and this server URL — keep them in sync via THIS script.

    ~/.virtualenvs/douanier/bin/python clients/refresh_openapi.py
"""
import json
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parent))  # the service package (app.py, config.py)

import app  # noqa: E402  (imported for its FastAPI instance)
import config  # noqa: E402

PUBLIC_BASE = "https://api.nech.pl"


def main() -> None:
    spec = app.app.openapi()
    spec["servers"] = [{"url": PUBLIC_BASE + config.ROOT_PATH}]
    out = HERE / "openapi.json"
    out.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n")
    ops = [o.get("operationId") for p in spec["paths"].values() for o in p.values()]
    print(f"wrote {out}  ({len(ops)} operations, server={spec['servers'][0]['url']})")


if __name__ == "__main__":
    main()
