"""Provider registry — defines supported integrations, their config fields, secret fields,
and webhook support.  Adding a new provider = add one entry here.
"""
from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


@dataclass(frozen=True)
class ProviderDef:
    """Static definition of a supported integration provider."""

    name: str
    display_name: str
    # Config keys that are safe to store plain and push to Cloud
    config_fields: tuple[str, ...]
    # Secret key names whose values are stored Fernet-encrypted in Core only
    secret_fields: tuple[str, ...]
    # None = no webhook support
    webhook_events: Optional[tuple[str, ...]] = None
    # True = webhook signing secret returned by provider after registration
    webhook_has_signing_secret: bool = False


PROVIDERS: dict[str, ProviderDef] = {
    "stripe": ProviderDef(
        name="stripe",
        display_name="Stripe",
        config_fields=("publishable_key", "account_id"),
        secret_fields=("secret_key",),
        webhook_events=(
            "payment_intent.succeeded",
            "payment_intent.payment_failed",
            "customer.subscription.created",
            "customer.subscription.updated",
            "customer.subscription.deleted",
            "checkout.session.completed",
        ),
        webhook_has_signing_secret=True,
    ),
    "resend": ProviderDef(
        name="resend",
        display_name="Resend",
        config_fields=("from_email", "from_name"),
        secret_fields=("api_key",),
        webhook_events=None,
    ),
    "slack": ProviderDef(
        name="slack",
        display_name="Slack",
        config_fields=("team_id", "team_name", "channel_id"),
        secret_fields=("bot_token",),
        webhook_events=None,
    ),
    "twilio": ProviderDef(
        name="twilio",
        display_name="Twilio",
        config_fields=("account_sid", "from_phone"),
        secret_fields=("auth_token",),
        webhook_events=("message.received",),
        webhook_has_signing_secret=False,
    ),
    "openai": ProviderDef(
        name="openai",
        display_name="OpenAI",
        config_fields=("model", "base_url"),
        secret_fields=("api_key",),
        webhook_events=None,
    ),
    "github": ProviderDef(
        name="github",
        display_name="GitHub",
        config_fields=("installation_id", "repo"),
        secret_fields=("app_private_key",),
        webhook_events=("push", "pull_request", "issues", "release"),
        webhook_has_signing_secret=True,
    ),
}


def get_provider(name: str) -> Optional[ProviderDef]:
    return PROVIDERS.get(name)


def supported_providers() -> list[str]:
    return list(PROVIDERS.keys())


def supports_webhooks(name: str) -> bool:
    p = get_provider(name)
    return p is not None and p.webhook_events is not None
