"""
Example: FastAPI webhook server that handles inbound SMS.
"""

import os
from fastapi import FastAPI, HTTPException, Request, Response
from agentphone import AgentPhone, construct_event, WebhookVerificationError

app = FastAPI()
client = AgentPhone(api_key=os.environ["AGENTPHONE_API_KEY"])

# Get your webhook secret from: client.webhooks.get().secret
WEBHOOK_SECRET = os.environ["AGENTPHONE_WEBHOOK_SECRET"]


@app.post("/webhook")
async def handle_webhook(request: Request):
    body = await request.body()
    signature = request.headers.get("X-Webhook-Signature", "")

    try:
        event = construct_event(body, signature, secret=WEBHOOK_SECRET)
    except WebhookVerificationError:
        raise HTTPException(status_code=403, detail="Invalid signature")

    if event.event == "agent.message":
        msg = event.data
        print(f"Inbound SMS from {msg.from_number}: {msg.message}")
        print(f"Conversation: {msg.conversation_id}")
        if event.recent_history:
            print(f"Last {len(event.recent_history)} messages:")
            for h in event.recent_history:
                print(f"  [{h.direction}] {h.content}")

    return Response(status_code=200)


@app.on_event("startup")
async def register_webhook():
    # Register this server as the webhook endpoint
    webhook = client.webhooks.set(
        url="https://your-server.com/webhook",
        context_limit=10,
    )
    print(f"Webhook registered. Secret: {webhook.secret}")
