"""JSON Schema validator for parser event output."""
from __future__ import annotations

import json
from pathlib import Path
from typing import Any

from jsonschema import Draft202012Validator

_SCHEMA_PATH = Path(__file__).parent.parent / "schemas" / "parser_event.schema.json"
_SCHEMA: dict[str, Any] | None = None


def _get_schema() -> dict[str, Any]:
    global _SCHEMA
    if _SCHEMA is None:
        _SCHEMA = json.loads(_SCHEMA_PATH.read_text())
    return _SCHEMA


def validate_parser_output(data: dict[str, Any]) -> list[str]:
    """Validate parser output against schema. Returns list of error messages (empty = valid)."""
    schema = _get_schema()
    validator = Draft202012Validator(schema)
    errors = sorted(validator.iter_errors(data), key=lambda e: list(e.path))
    return [f"{'.'.join(str(p) for p in e.path) or 'root'}: {e.message}" for e in errors]


def is_valid(data: dict[str, Any]) -> bool:
    return len(validate_parser_output(data)) == 0
