#!/usr/bin/env python3
"""Generate the OpenAPI spec and save it to openapi.json.

This script is used by the CI OpenAPI breaking-change check. It creates
the FastAPI app (without starting the server) and serialises the OpenAPI
schema to stdout or a file.

Usage:
    python scripts/generate_openapi.py [output_path]
"""

from __future__ import annotations

import json
import sys
from pathlib import Path

if __name__ == "__main__":
    # Add the backend directory to the path so we can import app modules.
    backend_root = Path(__file__).parent.parent
    sys.path.insert(0, str(backend_root))

    from app.config import Settings
    from app.main import create_app

    settings = Settings(
        database_path="/tmp/test.db",
        fail2ban_socket="/tmp/fake.sock",
        fail2ban_config_dir="/tmp/fail2ban",
        session_secret="openapi-script-secret-do-not-use-in-production",
        session_duration_minutes=60,
        timezone="UTC",
        log_level="critical",
    )

    app = create_app(settings=settings)
    spec = app.openapi()

    output = sys.argv[1] if len(sys.argv) > 1 else None
    if output:
        Path(output).write_text(json.dumps(spec, indent=2))
        print(f"OpenAPI spec written to {output}", file=sys.stderr)
    else:
        print(json.dumps(spec, indent=2))
