from __future__ import annotations

from django.apps import AppConfig
from django.utils.module_loading import autodiscover_modules


class ModulesConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "simorgh.apps.modules"
    label = "platform_modules"
    verbose_name = "Module system"

    def ready(self) -> None:
        # Seed permissions and events before discovery.
        from simorgh.apps.modules import events, permissions  # noqa: F401

        # Each business app may expose a top-level `module.py` that calls
        # `register_module(ModuleManifest(...))` to declare itself.
        autodiscover_modules("module")

        # Sync manifests to DB after migrations are complete.
        # Using post_migrate avoids the "DB access during app init" warning
        # and ensures the table exists when the handler runs.
        from django.db.models.signals import post_migrate

        post_migrate.connect(_sync_registry_to_db, sender=self)


def _sync_registry_to_db(sender, **kwargs):
    """Post-migrate handler: upsert Feature and ModuleCatalog rows."""
    try:
        from simorgh.apps.modules.services import (
            seed_default_domains,
            sync_features_to_db,
            sync_modules_to_db,
        )

        seed_default_domains()
        sync_features_to_db()
        sync_modules_to_db()
    except Exception:  # pragma: no cover
        pass  # never crash a migration run

