"""Database module with Registry pattern to prevent SQLAlchemy multiple classes errors.

This module implements the Registry pattern as specified in the project requirements
to ensure all models are properly registered and prevent SQLAlchemy "multiple classes" errors.
"""

from typing import Dict, Optional, Type

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import registry

# Create the registry
mapper_registry = registry()
Base = mapper_registry.generate_base()

# Model registry to track all models
_model_registry: Dict[str, Type] = {}


def register_model(model_class: Type) -> Type:
    """Register a model class to prevent SQLAlchemy multiple classes errors.

    Args:
        model_class: The model class to register

    Returns:
        The registered model class

    Raises:
        ValueError: If model is already registered

    """
    model_name = model_class.__name__
    if model_name in _model_registry:
        raise ValueError(f"Model {model_name} is already registered")

    _model_registry[model_name] = model_class
    return model_class


def get_registered_models() -> Dict[str, Type]:
    """Get all registered models.

    Returns:
        Dictionary of registered model names to classes

    """
    return _model_registry.copy()


def get_model_by_name(name: str) -> Optional[Type]:
    """Get a registered model by name.

    Args:
        name: Model name

    Returns:
        Model class if found, None otherwise

    """
    return _model_registry.get(name)


# Import all models to ensure they're registered
from .models import *  # noqa: F403, F401

__all__ = [
    "Base",
    "mapper_registry",
    "register_model",
    "get_registered_models",
    "get_model_by_name",
]
