from __future__ import annotations

from typing import TYPE_CHECKING

from amsdal_models.classes.class_loader import ModelClassLoader
from amsdal_utils.models.enums import ModuleType

if TYPE_CHECKING:
    from amsdal_models.classes.model import Model


def get_all_models() -> dict[type[Model], ModuleType]:
    """
    Scans configured AMSDAL modules to discover and load model classes with their scopes.

    Iterates through Core, Type, Contrib, and User modules defined in settings,
    using `ModelClassLoader` to import them.

    Returns:
        dict[type[Model], ModuleType]: A dict mapping model classes to their ModuleType (CORE, CONTRIB, USER).
    """
    from amsdal.configs.main import settings

    modules_to_scan = []

    if settings.CORE_MODELS_MODULE:
        modules_to_scan.append((settings.CORE_MODELS_MODULE, ModuleType.CORE))
    if settings.TYPE_MODELS_MODULE:
        modules_to_scan.append((settings.TYPE_MODELS_MODULE, ModuleType.CORE))

    for contrib in settings.CONTRIBS:
        if isinstance(contrib, str):
            package_name = contrib.rsplit('.', 2)[0]
            contrib_models_module = f'{package_name}.models'
            modules_to_scan.append((contrib_models_module, ModuleType.CONTRIB))

    if settings.USER_MODELS_MODULE:
        modules_to_scan.append((settings.USER_MODELS_MODULE, ModuleType.USER))

    all_loaded_classes = {}

    for module_path, module_type in modules_to_scan:
        try:
            loader = ModelClassLoader(module_path)
            loaded_classes = loader.load()

            for cls in loaded_classes:
                all_loaded_classes[cls] = module_type
        except ImportError:
            continue

    return all_loaded_classes
