#!/usr/bin/env -S uv run
# /// script
# requires-python = ">=3.8"
# dependencies = [
#     "jsonschema>=4.0.0",
# ]
# ///
"""
Validate that JSON schemas generated by Spectra conform to JSON Schema 2020-12.

Usage:
    uv run validate_json_schema.py <schema.json> [schema2.json ...]
    uv run validate_json_schema.py schemas/*.json

The script uses uv's inline script dependencies (PEP 723), so no separate
installation is needed - uv will automatically handle dependencies.
"""

import json
import sys

import jsonschema
from jsonschema import Draft202012Validator


def load_json_file(filepath):
    """Load JSON from a file"""
    with open(filepath, 'r') as f:
        return json.load(f)


def validate_schema(schema_path):
    """
    Validate a Spectra-generated JSON schema.

    Checks:
    1. Schema has $schema field pointing to 2020-12
    2. Schema is valid according to JSON Schema 2020-12 meta-schema

    Returns:
        True if valid, False otherwise
    """

    # Load the schema
    try:
        schema = load_json_file(schema_path)
    except Exception as e:
        print(f"❌ Failed to load schema: {e}")
        return False

    # Check 1: Verify $schema field exists
    if "$schema" not in schema:
        print("❌ Schema missing $schema field")
        return False

    schema_uri = schema["$schema"]

    # Check 2: Verify it's JSON Schema 2020-12
    if "2020-12" not in schema_uri:
        print("❌ Schema does not declare JSON Schema 2020-12")
        print(f"   Found: {schema_uri}")
        print("   Expected: https://json-schema.org/draft/2020-12/schema")
        return False
    else:
        print(f"✅ Schema declares: {schema_uri}")

    # Check 3: Validate schema structure against meta-schema
    try:
        Draft202012Validator.check_schema(schema)
        print("✅ Schema is valid JSON Schema 2020-12")
    except jsonschema.SchemaError as e:
        print(f"❌ Schema validation failed: {e.message}")
        if e.path:
            print(f"   Path: {list(e.path)}")
        if e.schema_path:
            print(f"   Schema path: {list(e.schema_path)}")
        return False

    return True


def main():
    if len(sys.argv) < 2:
        print("Usage: python validate_json_schema.py <schema.json> [schema2.json ...]")
        print("\nValidates that JSON schemas conform to JSON Schema 2020-12 specification.")
        print("\nExample:")
        print("  python validate_json_schema.py my_schema.json")
        sys.exit(1)

    all_valid = True

    for schema_file in sys.argv[1:]:
        if not validate_schema(schema_file):
            all_valid = False

    if all_valid:
        print("✅ All schemas are valid JSON Schema 2020-12!")
        sys.exit(0)
    else:
        print("❌ Some schemas failed validation")
        sys.exit(1)


if __name__ == "__main__":
    main()
