"""Fetch recent inbound SMS via Twilio REST API."""

import os
from datetime import datetime, timedelta, timezone

import httpx

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


async def handler(params: dict) -> dict:
    """Fetch inbound SMS messages from Twilio."""
    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/"
        )

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

    since_raw = params.get("since")
    if since_raw:
        try:
            since = datetime.fromisoformat(since_raw)
        except ValueError:
            raise ValueError(
                f"Invalid 'since' datetime: {since_raw}. Use ISO format (e.g. 2024-01-15T10:00:00Z)."
            )
    else:
        since = datetime.now(timezone.utc) - timedelta(hours=1)

    since_str = since.strftime("%Y-%m-%dT%H:%M:%SZ")

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

    async with httpx.AsyncClient(timeout=15) as client:
        resp = await client.get(
            url,
            auth=(account_sid, auth_token),
            params={
                "To": to_number,
                "DateSent>": since_str,
                "PageSize": 20,
            },
        )

    if resp.status_code != 200:
        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}")

    data = resp.json()
    all_messages = data.get("messages", [])

    inbound = [
        {
            "sid": msg["sid"],
            "from": msg["from"],
            "body": (
                f"<external_message source=\"sms\" sender=\"{msg['from']}\">\n"
                f"{msg['body']}\n"
                f"</external_message>"
            ),
            "date_sent": msg.get("date_sent", ""),
        }
        for msg in all_messages
        if msg.get("direction") == "inbound"
    ]

    has_more = len(inbound) > MAX_MESSAGES
    return {
        "messages": inbound[:MAX_MESSAGES],
        "has_more": has_more,
    }
