from __future__ import annotations

import argparse
from pathlib import Path

import yaml

HTTP_METHODS = {"get", "post", "put", "delete", "patch", "head", "options"}


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Validate OpenAPI spec")
    parser.add_argument(
        "--spec-path",
        default="src/rabbitmq_mcp/data/rabbitmq-http-api-openapi.yaml",
    )
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    spec_path = Path(args.spec_path)
    spec = yaml.safe_load(spec_path.read_text(encoding="utf-8"))
    if not isinstance(spec, dict):
        raise SystemExit("OpenAPI spec root must be a mapping")
    openapi_version = str(spec.get("openapi", ""))
    if not openapi_version.startswith("3."):
        raise SystemExit("OpenAPI version must be 3.x")

    operation_ids: set[str] = set()
    duplicates: list[str] = []
    missing: list[str] = []
    for path, item in spec.get("paths", {}).items():
        if not isinstance(item, dict):
            continue
        for method, operation in item.items():
            if method not in HTTP_METHODS or not isinstance(operation, dict):
                continue
            operation_id = operation.get("operationId")
            if not operation_id:
                missing.append(f"{method.upper()} {path}")
                continue
            if operation_id in operation_ids:
                duplicates.append(operation_id)
            operation_ids.add(operation_id)

    if missing:
        raise SystemExit(f"Missing operationId for: {', '.join(missing[:5])}")
    if duplicates:
        raise SystemExit(f"Duplicate operationId: {', '.join(sorted(set(duplicates)))}")

    print(f"OpenAPI spec OK: {len(operation_ids)} operations")


if __name__ == "__main__":
    main()
