"""WhatsApp Business Cloud API (Meta) — send text messages."""
import httpx
from app.config import settings


def _normalize_phone(phone: str) -> str:
    """Remove non-digits and leading +. Expects E.164 format input."""
    digits = "".join(c for c in phone if c.isdigit())
    return digits


async def send_whatsapp(phone: str, message: str) -> bool:
    """
    Send a WhatsApp text message via Meta Business Cloud API.
    Returns True on success, False on failure.

    Note: For business-initiated conversations (not within 24h of user reply),
    Meta requires approved message templates. This function sends a free-form
    text message which works during testing or within 24h session windows.
    Switch to send_whatsapp_template() for production outbound notifications.
    """
    if not settings.WHATSAPP_ACCESS_TOKEN or not settings.WHATSAPP_PHONE_NUMBER_ID:
        print("[whatsapp] credentials not configured — skipping")
        return False

    to = _normalize_phone(phone)
    if not to:
        return False

    url = f"https://graph.facebook.com/v19.0/{settings.WHATSAPP_PHONE_NUMBER_ID}/messages"
    headers = {
        "Authorization": f"Bearer {settings.WHATSAPP_ACCESS_TOKEN}",
        "Content-Type": "application/json",
    }
    payload = {
        "messaging_product": "whatsapp",
        "to": to,
        "type": "text",
        "text": {"body": message},
    }

    try:
        async with httpx.AsyncClient(timeout=10) as client:
            resp = await client.post(url, json=payload, headers=headers)
            if resp.status_code != 200:
                print(f"[whatsapp] API error {resp.status_code}: {resp.text[:200]}")
                return False
        return True
    except Exception as e:
        print(f"[whatsapp] send error: {e}")
        return False


async def send_whatsapp_template(phone: str, template_name: str, params: list[str],
                                  language: str = "id") -> bool:
    """
    Send a Meta-approved template message.
    params = list of parameter values for {{1}}, {{2}}, etc. in the template body.
    """
    if not settings.WHATSAPP_ACCESS_TOKEN or not settings.WHATSAPP_PHONE_NUMBER_ID:
        return False

    to = _normalize_phone(phone)
    if not to:
        return False

    components = []
    if params:
        components.append({
            "type": "body",
            "parameters": [{"type": "text", "text": p} for p in params],
        })

    url = f"https://graph.facebook.com/v19.0/{settings.WHATSAPP_PHONE_NUMBER_ID}/messages"
    headers = {
        "Authorization": f"Bearer {settings.WHATSAPP_ACCESS_TOKEN}",
        "Content-Type": "application/json",
    }
    payload = {
        "messaging_product": "whatsapp",
        "to": to,
        "type": "template",
        "template": {
            "name": template_name,
            "language": {"code": language},
            "components": components,
        },
    }

    try:
        async with httpx.AsyncClient(timeout=10) as client:
            resp = await client.post(url, json=payload, headers=headers)
            if resp.status_code != 200:
                print(f"[whatsapp] template error {resp.status_code}: {resp.text[:200]}")
                return False
        return True
    except Exception as e:
        print(f"[whatsapp] template send error: {e}")
        return False
