"""Send SMS via Twilio REST API."""

import os

import httpx

TWILIO_API_BASE = "https://api.twilio.com/2010-04-01/Accounts"


async def handler(params: dict) -> dict:
    """Send an SMS via Twilio REST API."""
    to = params["to"]
    body = params["body"]

    account_sid = os.environ.get("TWILIO_ACCOUNT_SID")
    if not account_sid:
        raise ValueError(
            "TWILIO_ACCOUNT_SID not set. Get it from https://console.twilio.com/"
        )

    auth_token = os.environ.get("TWILIO_AUTH_TOKEN")
    if not auth_token:
        raise ValueError(
            "TWILIO_AUTH_TOKEN not set. Get it from https://console.twilio.com/"
        )

    from_number = os.environ.get("TWILIO_PHONE_NUMBER")
    if not from_number:
        raise ValueError(
            "TWILIO_PHONE_NUMBER not set. "
            "Set it to your Twilio phone number in E.164 format."
        )

    if len(body) > 1600:
        raise ValueError(f"SMS body too long ({len(body)} chars). Max 1600.")

    url = f"{TWILIO_API_BASE}/{account_sid}/Messages.json"

    async with httpx.AsyncClient(timeout=15) as client:
        resp = await client.post(
            url,
            auth=(account_sid, auth_token),
            data={
                "To": to,
                "From": from_number,
                "Body": body,
            },
        )

    if resp.status_code == 201:
        data = resp.json()
        return {
            "status": f"SMS sent to {to}",
            "sid": data.get("sid", ""),
        }

    try:
        error_data = resp.json()
        error_msg = error_data.get("message", resp.text)
    except Exception:
        error_msg = resp.text

    raise ValueError(f"Twilio API error ({resp.status_code}): {error_msg}")
