"""Sends the one-time code as a WhatsApp Authentication template through the Meta Graph API."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Protocol

import httpx


@dataclass(frozen=True)
class WhatsAppConfig:
    phone_number_id: str
    access_token: str
    template_name: str
    template_language: str
    include_button: bool


class DeliveryError(Exception):
    """The code could not be delivered. The message is safe to log and never contains the access token."""


class Sender(Protocol):
    async def send_otp(self, cfg: WhatsAppConfig, to_e164: str, code: str) -> str:
        """Send the code and return the WhatsApp message id."""

    async def send_text(self, cfg: WhatsAppConfig, to_e164: str, body: str) -> str:
        """Send a plain message (only allowed inside the 24 hours after the person wrote to the number)."""

    async def check(self, cfg: WhatsAppConfig) -> dict:
        """Ask Meta about the sending number; raises DeliveryError when the token or number is wrong."""


class GraphSender:
    def __init__(self, graph_base: str, timeout: float, transport: httpx.AsyncBaseTransport | None = None) -> None:
        self._base = graph_base.rstrip("/")
        self._timeout = timeout
        self._transport = transport

    def _client(self) -> httpx.AsyncClient:
        return httpx.AsyncClient(timeout=self._timeout, transport=self._transport)

    @staticmethod
    def _error(cfg: WhatsAppConfig, response: httpx.Response) -> DeliveryError:
        try:
            err = response.json().get("error", {})
            text = f"{err.get('message', 'request refused')} (Meta code {err.get('code', response.status_code)})"
        except ValueError:
            text = f"Meta answered HTTP {response.status_code}"
        return DeliveryError(text.replace(cfg.access_token, "***"))

    async def send_otp(self, cfg: WhatsAppConfig, to_e164: str, code: str) -> str:
        components: list[dict] = [{"type": "body", "parameters": [{"type": "text", "text": code}]}]
        if cfg.include_button:  # the copy-code button of an Authentication template carries the same code
            components.append({
                "type": "button", "sub_type": "url", "index": "0",
                "parameters": [{"type": "text", "text": code}],
            })
        payload = {
            "messaging_product": "whatsapp",
            "to": to_e164.lstrip("+"),
            "type": "template",
            "template": {
                "name": cfg.template_name,
                "language": {"code": cfg.template_language},
                "components": components,
            },
        }
        try:
            async with self._client() as client:
                response = await client.post(
                    f"{self._base}/{cfg.phone_number_id}/messages", json=payload,
                    headers={"Authorization": f"Bearer {cfg.access_token}"},
                )
        except httpx.HTTPError as exc:
            raise DeliveryError(f"could not reach Meta ({type(exc).__name__})") from exc
        if response.status_code >= 400:
            raise self._error(cfg, response)
        try:
            return response.json()["messages"][0]["id"]
        except (ValueError, KeyError, IndexError, TypeError) as exc:
            raise DeliveryError("Meta accepted the request but returned no message id") from exc

    async def send_text(self, cfg: WhatsAppConfig, to_e164: str, body: str) -> str:
        payload = {
            "messaging_product": "whatsapp",
            "to": to_e164.lstrip("+"),
            "type": "text",
            "text": {"preview_url": False, "body": body},
        }
        try:
            async with self._client() as client:
                response = await client.post(
                    f"{self._base}/{cfg.phone_number_id}/messages", json=payload,
                    headers={"Authorization": f"Bearer {cfg.access_token}"},
                )
        except httpx.HTTPError as exc:
            raise DeliveryError(f"could not reach Meta ({type(exc).__name__})") from exc
        if response.status_code >= 400:
            raise self._error(cfg, response)
        try:
            return response.json()["messages"][0]["id"]
        except (ValueError, KeyError, IndexError, TypeError) as exc:
            raise DeliveryError("Meta accepted the request but returned no message id") from exc

    async def check(self, cfg: WhatsAppConfig) -> dict:
        try:
            async with self._client() as client:
                response = await client.get(
                    f"{self._base}/{cfg.phone_number_id}",
                    params={"fields": "display_phone_number,verified_name,quality_rating"},
                    headers={"Authorization": f"Bearer {cfg.access_token}"},
                )
        except httpx.HTTPError as exc:
            raise DeliveryError(f"could not reach Meta ({type(exc).__name__})") from exc
        if response.status_code >= 400:
            raise self._error(cfg, response)
        return response.json()
