"""Official Meta WhatsApp Cloud API adapter (switch with PROVIDER=cloud_api).

NOT tested against a live WABA - it is the upgrade path. Each event needs an APPROVED template in
WhatsApp Manager whose name = `cloud_template` in templates.yml and whose body variables {{1}},{{2}}..
match the order of `cloud_params`.
"""
import httpx

from .. import templating
from ..config import settings
from .base import BaseAdapter, SendError


class CloudApiAdapter(BaseAdapter):
    name = "cloud_api"

    def __init__(self):
        self.url = f"https://graph.facebook.com/{settings.cloud_version}/{settings.cloud_phone_id}/messages"
        self.http = httpx.Client(timeout=30, headers={"Authorization": f"Bearer {settings.cloud_token}"})

    def connection_state(self) -> str:
        return "open" if settings.cloud_token and settings.cloud_phone_id else "not_configured"

    def send(self, msg) -> str | None:
        name, params = templating.cloud_template(msg.event)
        if not name:
            raise SendError(f"no cloud_template defined for event {msg.event}", retryable=False)
        variables = {"site": settings.site_name, **(msg.vars or {})}
        lang = "ar" if (msg.locale or "").startswith("ar") else "en"
        body = {
            "messaging_product": "whatsapp", "to": msg.to_phone, "type": "template",
            "template": {"name": name, "language": {"code": lang}, "components": [{
                "type": "body",
                "parameters": [{"type": "text", "text": str(variables.get(p, "") or "-")} for p in params],
            }]},
        }
        try:
            r = self.http.post(self.url, json=body)
        except httpx.HTTPError as exc:
            raise SendError(f"cloud api unreachable: {exc}") from exc
        if r.status_code >= 300:
            raise SendError(f"HTTP {r.status_code}: {r.text[:500]}", retryable=r.status_code >= 500 or r.status_code == 429)
        ids = r.json().get("messages") or []
        return ids[0].get("id") if ids else None
