"""SchemaAdapter - Pydantic model loading.

Contract: CNT-T3-ADP-003
"""

from pathlib import Path
from typing import Any

from pydantic import BaseModel, ValidationError


class SchemaAdapter:
    """Adapter for Pydantic schema operations."""

    def __init__(self, templates_dir: Path | None = None) -> None:
        """Initialize schema adapter.

        Args:
            templates_dir: Directory containing schema templates
        """
        self._templates_dir = templates_dir

    def validate(self, data: dict[str, Any], schema_class: type[BaseModel]) -> bool:
        """Validate data against a Pydantic model.

        Args:
            data: Data to validate
            schema_class: Pydantic model class

        Returns:
            True if valid
        """
        try:
            schema_class.model_validate(data)
            return True
        except ValidationError:
            return False

    def validate_with_errors(
        self, data: dict[str, Any], schema_class: type[BaseModel]
    ) -> tuple[bool, list[str]]:
        """Validate data and return errors if any.

        Args:
            data: Data to validate
            schema_class: Pydantic model class

        Returns:
            Tuple of (is_valid, list of error messages)
        """
        try:
            schema_class.model_validate(data)
            return True, []
        except ValidationError as e:
            errors = [f"{err['loc']}: {err['msg']}" for err in e.errors()]
            return False, errors

    def list_schemas(self) -> list[str]:
        """List available schema templates.

        Returns:
            List of schema names
        """
        if not self._templates_dir or not self._templates_dir.exists():
            return []

        schemas = []
        for yaml_file in self._templates_dir.glob("*.yaml"):
            schemas.append(yaml_file.stem)
        return sorted(schemas)
