"""
Centralized SST path resolver.

All Pydantic models should use this to resolve SST file paths.
Paths are defined ONCE in __index.yaml - no hardcoding in Python.

Usage:
    from lightwave.schema.core.paths import get_sst_path, DEFINITIONS_DIR

    # Get path by registry key
    path = get_sst_path("layouts")  # Returns .../definitions/ui/layouts/layouts.yaml

    # Get definitions directory
    DEFINITIONS_DIR  # Returns .../definitions/
"""

from functools import lru_cache
from pathlib import Path

import yaml

# Definitions directory (relative to this file)
# core/paths.py -> schema/ -> definitions/
DEFINITIONS_DIR = Path(__file__).parent.parent / "definitions"


@lru_cache(maxsize=1)
def _load_index() -> dict[str, str]:
    """
    Load schema registry from __index.yaml.

    Returns:
        Dictionary mapping schema keys to relative paths
    """
    index_path = DEFINITIONS_DIR / "__index.yaml"
    if not index_path.exists():
        raise FileNotFoundError(f"Schema index not found: {index_path}")

    with open(index_path) as f:
        data = yaml.safe_load(f)

    # Merge schemas and aliases
    schemas = dict(data.get("schemas", {}))
    aliases = data.get("aliases", {})

    for alias, path in aliases.items():
        if alias not in schemas:
            schemas[alias] = path

    return schemas


def get_schema_registry() -> dict[str, str]:
    """
    Get the full schema registry.

    Returns:
        Dictionary mapping schema keys to relative paths
    """
    return _load_index()


def get_sst_path(schema_key: str) -> Path:
    """
    Get the full path to an SST file by its registry key.

    Args:
        schema_key: The key from __index.yaml (e.g., "layouts", "field_options")

    Returns:
        Full Path to the YAML file

    Raises:
        KeyError: If schema_key not found in registry

    Usage:
        path = get_sst_path("layouts")
        # Returns: .../definitions/ui/layouts/layouts.yaml
    """
    registry = _load_index()
    if schema_key not in registry:
        available = sorted(registry.keys())
        raise KeyError(f"Schema '{schema_key}' not found in __index.yaml. Available keys: {available}")
    return DEFINITIONS_DIR / registry[schema_key]


def clear_cache() -> None:
    """Clear the cached registry (useful for testing)."""
    _load_index.cache_clear()
