from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _


# ---------------------------------------------------------------------------
# Risks AppConfig
# ---------------------------------------------------------------------------
class RisksConfig(AppConfig):
    """App configuration for the risks module."""
    default_auto_field = "django.db.models.BigAutoField"
    name = "risks"
    verbose_name = _("Risk Management")

    def ready(self):
        """
        Initialize signals and ensure NotificationRules exist for all
        NotificationKind choices. Ignores database errors during migration.
        """
        import risks.signals  # noqa: F401 (ensure signal handlers are loaded)

        try:
            from django.db.utils import OperationalError, ProgrammingError
            from .models import NotificationRule, NotificationKind

            # Test DB availability
            NotificationRule.objects.count()
        except (OperationalError, ProgrammingError):
            # Happens during migrate or before tables exist
            return

        # Ensure all NotificationKind values have a corresponding NotificationRule
        existing = set(NotificationRule.objects.values_list("kind", flat=True))
        for kind, _label in NotificationKind.choices:
            if kind not in existing:
                NotificationRule.objects.create(kind=kind)
