"""Call-provider registry.

The active provider is chosen by settings.AI_CALL_PROVIDER:

    mock        — simulated lifecycle, no network (default offline)
    selfhosted  — the open-source calling platform (platform/services/*)
    hunar       — Hunar AI's hosted outbound calling API

Everything downstream (queueing, webhooks, scoring, UI) is provider-agnostic.

NOTE: `mock` is the DEFAULT. It fabricates a call id and simulates the whole
lifecycle locally, so statuses, transcripts and summaries all appear even though
no phone is ever dialled. If real calls are expected, AI_CALL_PROVIDER must be
set explicitly.
"""

from django.conf import settings


class ProviderNotConfigured(RuntimeError):
    """No real calling backend is configured, and simulation is not opted into."""


def get_provider():
    """Return the configured calling backend.

    `mock` fabricates the entire call lifecycle locally — it reports DIALING,
    CONNECTED and COMPLETED and writes a generated transcript/score without ever
    dialling a phone. Because that is indistinguishable from a real result once
    stored, it is NO LONGER the silent default: using it now requires an explicit
    `AI_CALL_ALLOW_SIMULATED=true`. Without a real provider configured, calling
    fails loudly instead of inventing a successful call.

    The mock provider itself is unchanged and still available — it is only
    prevented from standing in for a real call by accident.
    """
    name = (getattr(settings, "AI_CALL_PROVIDER", "") or "").lower()
    if name == "selfhosted":
        from .selfhosted import SelfHostedProvider
        return SelfHostedProvider()
    if name == "hunar":
        from .hunar import HunarProvider
        return HunarProvider()

    if name == "mock" and getattr(settings, "AI_CALL_ALLOW_SIMULATED", False):
        from .mock import MockProvider
        return MockProvider()

    if name == "mock":
        raise ProviderNotConfigured(
            "AI_CALL_PROVIDER=mock only simulates calls and never dials a phone. "
            "Set AI_CALL_PROVIDER=hunar (with HUNAR_API_KEY and HUNAR_AGENT_ID) to "
            "place real calls, or AI_CALL_ALLOW_SIMULATED=true to deliberately run "
            "the local simulation."
        )
    raise ProviderNotConfigured(
        "AI calling is not configured. Set AI_CALL_PROVIDER=hunar with "
        "HUNAR_API_KEY, HUNAR_AGENT_ID and a publicly reachable PUBLIC_BASE_URL."
    )
