"""
Auto-discover and load all database models.

This module automatically imports all model files from the apps directory
to ensure they are registered with SQLAlchemy before the application starts.
This prevents circular import issues and relationship resolution errors.

No manual maintenance required - just create your model files in the standard
location: src/apps/<app_name>/models/<model_file>.py
"""

import pkgutil
import importlib
from pathlib import Path


def load_all_models():
    """
    Auto-discover and import all model files from apps.
    
    Searches through all app directories in src/apps and imports any Python
    modules found in their models subdirectories. This ensures all SQLAlchemy
    models are registered before the application starts.
    """
    apps_dir = Path(__file__).parent.parent / "apps"
    
    if not apps_dir.exists():
        return
    
    for app_path in apps_dir.iterdir():
        # Skip non-directories and private/internal directories
        if not app_path.is_dir() or app_path.name.startswith("_"):
            continue
            
        models_path = app_path / "models"
        
        # Skip if no models directory exists for this app
        if not models_path.exists() or not models_path.is_dir():
            continue
        
        # Import all Python modules in the models directory
        for module_info in pkgutil.iter_modules([str(models_path)]):
            # Skip __init__.py and private modules
            if module_info.name.startswith("_"):
                continue
                
            module_name = f"src.apps.{app_path.name}.models.{module_info.name}"
            try:
                importlib.import_module(module_name)
            except Exception as e:
                # Log the error but don't crash the application
                print(f"Warning: Failed to import model {module_name}: {e}")
