"""
Lightweight schema registry for receipt JSON Schemas.

This module indexes schemas under receipts/schemas/ by their $id so callers
can validate payloads by schema ID (dataschema).
"""

from __future__ import annotations

import json
from functools import lru_cache
from pathlib import Path
from typing import Dict

from jsonschema import Draft202012Validator

SCHEMAS_DIR = Path(__file__).resolve().parent / "schemas"


@lru_cache(maxsize=64)
def _index_schemas() -> Dict[str, Draft202012Validator]:
    registry: Dict[str, Draft202012Validator] = {}
    if not SCHEMAS_DIR.exists():
        return registry

    for schema_path in SCHEMAS_DIR.rglob("*.json"):
        try:
            schema = json.loads(schema_path.read_text(encoding="utf-8"))
        except Exception:
            continue
        schema_id = schema.get("$id")
        if not schema_id:
            continue
        try:
            registry[schema_id] = Draft202012Validator(schema)
        except Exception:
            # Skip invalid schemas
            continue
    return registry


def get_validator(schema_id: str) -> Draft202012Validator:
    """
    Get a Draft202012Validator for the given schema ID.

    Raises KeyError if the schema ID is not known.
    """
    registry = _index_schemas()
    if schema_id not in registry:
        raise KeyError(f"Schema not found: {schema_id}")
    return registry[schema_id]


def list_schema_ids():
    """Return all indexed schema IDs."""
    return list(_index_schemas().keys())

