"""Provider registry — maps provider_kind to channel adapters."""
from __future__ import annotations

from typing import Any

from app.providers.contracts import ChannelProvider
from app.providers.mock_sms import MockSMSProvider, StubFutureChannelProvider
from app.providers.payamak import PayamakSMSProvider

_REGISTRY: dict[str, ChannelProvider] = {}


def _bootstrap() -> None:
    if _REGISTRY:
        return
    mock = MockSMSProvider()
    payamak = PayamakSMSProvider()
    _REGISTRY["mock"] = mock
    _REGISTRY["payamak"] = payamak
    for kind, channel in (
        ("smtp", "email"),
        ("fcm", "push"),
        ("whatsapp_cloud", "whatsapp"),
        ("telegram_bot", "telegram"),
        ("rubika_bot", "rubika"),
        ("voice_gateway", "voice"),
        ("custom", "future"),
    ):
        _REGISTRY[kind] = StubFutureChannelProvider(kind, channel)


def get_provider(provider_kind: str) -> ChannelProvider:
    _bootstrap()
    if provider_kind not in _REGISTRY:
        raise KeyError(f"Unknown provider kind: {provider_kind}")
    return _REGISTRY[provider_kind]


def list_registered_provider_kinds() -> list[str]:
    _bootstrap()
    return sorted(_REGISTRY.keys())


def reset_provider_registry_for_tests(mock: MockSMSProvider | None = None) -> MockSMSProvider:
    """Replace mock instance so tests can inspect send calls."""
    global _REGISTRY
    _REGISTRY = {}
    instance = mock or MockSMSProvider()
    _REGISTRY["mock"] = instance
    _REGISTRY["payamak"] = PayamakSMSProvider()
    for kind, channel in (
        ("smtp", "email"),
        ("fcm", "push"),
        ("whatsapp_cloud", "whatsapp"),
        ("telegram_bot", "telegram"),
        ("rubika_bot", "rubika"),
        ("voice_gateway", "voice"),
        ("custom", "future"),
    ):
        _REGISTRY[kind] = StubFutureChannelProvider(kind, channel)
    return instance


def supported_channels() -> list[dict[str, Any]]:
    return [
        {"channel": "sms", "status": "active", "providers": ["mock", "payamak"]},
        {"channel": "email", "status": "planned", "providers": ["smtp"]},
        {"channel": "push", "status": "planned", "providers": ["fcm"]},
        {"channel": "whatsapp", "status": "planned", "providers": ["whatsapp_cloud"]},
        {"channel": "telegram", "status": "planned", "providers": ["telegram_bot"]},
        {"channel": "rubika", "status": "planned", "providers": ["rubika_bot"]},
        {"channel": "voice", "status": "planned", "providers": ["voice_gateway"]},
        {"channel": "future", "status": "extensible", "providers": ["custom"]},
    ]
