"""WhatsApp Business Cloud API integration via Meta Graph API."""

import os

import httpx

GRAPH_API_VERSION = "v21.0"


def _config() -> tuple[str, str]:
    """Return (token, phone_number_id) or raise with setup instructions."""
    token = os.environ.get("WHATSAPP_TOKEN")
    phone_id = os.environ.get("WHATSAPP_PHONE_NUMBER_ID")

    if not token:
        raise ValueError(
            "WHATSAPP_TOKEN not set. See SKILL.md for full setup instructions. "
            "Create a Meta Business app, add WhatsApp, create a system user, "
            "and generate a permanent token with whatsapp_business_messaging permission."
        )
    if not phone_id:
        raise ValueError(
            "WHATSAPP_PHONE_NUMBER_ID not set. Find it in your Meta app dashboard "
            "under WhatsApp > API Setup."
        )
    return token, phone_id


async def handler(params: dict) -> dict:
    """Handle WhatsApp operations."""
    action = params["action"]
    token, phone_id = _config()

    try:
        async with httpx.AsyncClient(timeout=30) as client:
            if action == "send_message":
                return await _send_message(client, token, phone_id, params)
            elif action == "send_template":
                return await _send_template(client, token, phone_id, params)
            else:
                return {"success": False, "message": f"Unknown action: {action}", "data": {}}
    except ValueError:
        raise
    except httpx.HTTPStatusError as e:
        error_body = e.response.text[:500]
        return {"success": False, "message": f"WhatsApp API error ({e.response.status_code}): {error_body}", "data": {}}
    except Exception as e:
        return {"success": False, "message": f"Error: {e}", "data": {}}


async def _send_message(client: httpx.AsyncClient, token: str, phone_id: str, params: dict) -> dict:
    to = params.get("to")
    text = params.get("text")
    if not to or not text:
        raise ValueError("'to' and 'text' are required for send_message")

    url = f"https://graph.facebook.com/{GRAPH_API_VERSION}/{phone_id}/messages"
    resp = await client.post(
        url,
        headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
        json={
            "messaging_product": "whatsapp",
            "to": to.replace("+", "").replace("-", "").replace(" ", ""),
            "type": "text",
            "text": {"body": text},
        },
    )
    resp.raise_for_status()
    data = resp.json()

    msg_id = ""
    if data.get("messages"):
        msg_id = data["messages"][0].get("id", "")

    return {
        "success": True,
        "message": f"WhatsApp message sent to {to}",
        "data": {"message_id": msg_id},
    }


async def _send_template(client: httpx.AsyncClient, token: str, phone_id: str, params: dict) -> dict:
    to = params.get("to")
    template_name = params.get("template_name")
    if not to or not template_name:
        raise ValueError("'to' and 'template_name' are required for send_template")

    language = params.get("template_language", "en_US")
    template_params = params.get("template_params", [])

    template = {
        "name": template_name,
        "language": {"code": language},
    }
    if template_params:
        template["components"] = [{
            "type": "body",
            "parameters": [{"type": "text", "text": p} for p in template_params],
        }]

    url = f"https://graph.facebook.com/{GRAPH_API_VERSION}/{phone_id}/messages"
    resp = await client.post(
        url,
        headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
        json={
            "messaging_product": "whatsapp",
            "to": to.replace("+", "").replace("-", "").replace(" ", ""),
            "type": "template",
            "template": template,
        },
    )
    resp.raise_for_status()
    data = resp.json()

    msg_id = ""
    if data.get("messages"):
        msg_id = data["messages"][0].get("id", "")

    return {
        "success": True,
        "message": f"WhatsApp template '{template_name}' sent to {to}",
        "data": {"message_id": msg_id},
    }
