"""
HTTP Routes Module

Provides FastAPI HTTP endpoints for Twilio webhooks.
"""

from fastapi import APIRouter, Request
from fastapi.responses import PlainTextResponse

from ..twilio_integration import get_twilio_client
from ..dialogue import call_state_manager
from ..config import log_call

router = APIRouter()


@router.post("/incoming-call")
async def incoming_call():
    """
    Twilio webhook for incoming calls.

    Returns TwiML with greeting and WebSocket stream connection.
    """
    helper = get_twilio_client()
    twiml = helper.build_greeting_twiml()
    return PlainTextResponse(twiml, media_type="application/xml")


@router.post("/speak")
async def speak():
    """
    TwiML template endpoint for AI speech.

    Note: This is a template reference, not typically called directly.
    """
    helper = get_twilio_client()
    twiml = helper.build_say_twiml("{{MESSAGE}}")
    return PlainTextResponse(twiml, media_type="application/xml")


@router.post("/stream")
async def stream():
    """
    Resume audio streaming after TTS.

    Called by Twilio after <Say> completes.
    """
    helper = get_twilio_client()
    twiml = helper.build_stream_twiml()
    return PlainTextResponse(twiml, media_type="application/xml")


@router.post("/hangup")
async def hangup():
    """
    Terminate call.

    Returns TwiML with <Hangup/>.
    """
    helper = get_twilio_client()
    twiml = helper.build_hangup_twiml()
    return PlainTextResponse(twiml, media_type="application/xml")


@router.post("/call-status")
async def call_status(request: Request):
    """
    Twilio webhook for call status updates.

    Marks calls as ended when status is terminal.
    """
    try:
        # Try to parse as JSON first
        data = await request.json()
    except Exception:
        # Fall back to form data
        form = await request.form()
        data = dict(form)

    call_sid = data.get("CallSid")
    status = data.get("CallStatus")

    if status in ["completed", "busy", "failed", "no-answer"]:
        call_state_manager.mark_ended(call_sid)
        log_call.info("call=%s status=%s marking as ended", call_sid, status)

    return {"status": "ok"}
