#!/usr/bin/env python3
"""Quality Gate: Contract Validation.

Loads every *.schema.json in contracts/ and verifies it is valid JSON Schema.
Exits 0 on success, 1 on failure.
"""

from __future__ import annotations

import json
import sys
from pathlib import Path

from abi_control_core.contracts import CONTRACTS_DIR


def main() -> int:
    schemas = sorted(CONTRACTS_DIR.glob("*.schema.json"))
    if not schemas:
        print("FAIL: No schema files found in contracts/")
        return 1

    errors: list[str] = []
    for schema_path in schemas:
        try:
            with open(schema_path, encoding="utf-8") as f:
                data = json.load(f)
            if not isinstance(data, dict):
                errors.append(f"{schema_path.name}: root is not an object")
            elif "$schema" not in data:
                errors.append(f"{schema_path.name}: missing $schema field")
        except json.JSONDecodeError as e:
            errors.append(f"{schema_path.name}: invalid JSON — {e}")

    if errors:
        print(f"FAIL: {len(errors)} schema error(s):")
        for err in errors:
            print(f"  - {err}")
        return 1

    print(f"PASS: {len(schemas)} schemas validated successfully")
    return 0


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