import logging

from django.apps import AppConfig
from django.conf import settings

logger = logging.getLogger(__name__)

#: Settings each provider needs before it can place a call. Names only — values
#: are never logged.
REQUIRED_BY_PROVIDER = {
    "hunar": ("HUNAR_API_KEY", "HUNAR_AGENT_ID", "HUNAR_BASE_URL"),
    "selfhosted": ("AI_PLATFORM_URL",),
}


class AiCallsConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "apps.ai_calls"
    verbose_name = "AI Screening Calls"

    def ready(self):
        """Report the AI-calling configuration once, at startup.

        Says exactly which variables are missing so a failed call never has to be
        diagnosed from the UI. Secret VALUES are never logged — only whether each
        name is set. Never raises: a misconfiguration must not stop the server,
        the call endpoints already refuse with a clear error.
        """
        try:
            self._log_call_config()
        except Exception:  # noqa: BLE001 — startup logging must never break boot
            logger.exception("[AI_CALL_CONFIG] Could not verify AI calling configuration")

    @staticmethod
    def _log_call_config():
        provider = (getattr(settings, "AI_CALL_PROVIDER", "") or "").lower()
        allow_sim = bool(getattr(settings, "AI_CALL_ALLOW_SIMULATED", False))

        if provider == "mock":
            if allow_sim:
                logger.warning(
                    "[AI_CALL_CONFIG] AI_CALL_PROVIDER=mock with "
                    "AI_CALL_ALLOW_SIMULATED=true — calls are SIMULATED locally and "
                    "no phone will ring. Set AI_CALL_PROVIDER=hunar for real calls."
                )
            else:
                logger.error(
                    "[AI_CALL_CONFIG] AI_CALL_PROVIDER=mock — AI calling is DISABLED "
                    "(simulation is not permitted without AI_CALL_ALLOW_SIMULATED=true). "
                    "Set AI_CALL_PROVIDER=hunar to place real calls."
                )
            return

        required = REQUIRED_BY_PROVIDER.get(provider)
        if required is None:
            logger.error(
                "[AI_CALL_CONFIG] AI_CALL_PROVIDER=%r is not a known provider "
                "(expected one of: hunar, selfhosted, mock). AI calling is disabled.",
                provider or "(unset)",
            )
            return

        missing = [n for n in required if not str(getattr(settings, n, "") or "").strip()]
        if missing:
            logger.error(
                "[AI_CALL_CONFIG] AI_CALL_PROVIDER=%s but %s not set in %s. "
                "AI calling will refuse with a configuration error instead of "
                "simulating a call. Add the value(s) and restart the backend.",
                provider, ", ".join(missing), settings.BASE_DIR / ".env",
            )
        else:
            # Names and lengths only — never the secret itself.
            logger.info(
                "[AI_CALL_CONFIG] AI_CALL_PROVIDER=%s ready: %s",
                provider,
                ", ".join(
                    f"{n}=set({len(str(getattr(settings, n)))} chars)"
                    if "KEY" in n or "SECRET" in n or "TOKEN" in n
                    else f"{n}={getattr(settings, n)}"
                    for n in required
                ),
            )

        public = (getattr(settings, "PUBLIC_BASE_URL", "") or "").strip()
        if provider == "hunar" and (
            not public or public.startswith("http://localhost") or public.startswith("http://127.")
        ):
            logger.warning(
                "[AI_CALL_CONFIG] PUBLIC_BASE_URL=%s is not reachable from the "
                "internet. Hunar reports call progress to the callbacks configured "
                "on its agent; until those point at a public "
                "<host>/api/v1/ai-calls/{webhook,transcript,completed}, a placed "
                "call stays at Dialing.", public or "(unset)",
            )
