#!/usr/bin/env python3
"""Webhook handler example using the HAX Python SDK with FastAPI.

This example demonstrates how to:
1. Set up a FastAPI endpoint to receive HAX webhooks
2. Verify webhook signatures for security
3. Process different event types

Usage:
    pip install fastapi uvicorn
    export HAX_WEBHOOK_SECRET="whsec_..."
    python webhook_handler.py
"""

import os

import uvicorn
from fastapi import FastAPI, Header, HTTPException, Request

from hax import parse_event, verify_signature

app = FastAPI(title="HAX Webhook Handler")

# Get webhook secret from environment
WEBHOOK_SECRET = os.environ.get("HAX_WEBHOOK_SECRET", "")


@app.post("/hax/webhook")
async def hax_webhook(
    request: Request,
    x_hax_signature: str = Header(default=""),
):
    """Handle incoming HAX webhook events."""
    # Read raw body for signature verification
    body = await request.body()

    # Verify the signature
    if WEBHOOK_SECRET and not verify_signature(
        payload=body,
        signature=x_hax_signature,
        secret=WEBHOOK_SECRET,
    ):
        raise HTTPException(status_code=401, detail="Invalid signature")

    # Parse the event
    event = parse_event(body)

    print(f"Received event: {event.type}")
    print(f"Request ID: {event.request_id}")

    # Handle different event types
    if event.type == "request.completed":
        handle_completed(event)
    elif event.type == "request.opened":
        handle_opened(event)
    elif event.type == "request.expired":
        handle_expired(event)
    else:
        print(f"Unknown event type: {event.type}")

    return {"status": "ok"}


def handle_completed(event):
    """Handle a completed request event."""
    print(f"Request {event.request_id} completed!")
    print(f"Response: {event.response}")

    # Access metadata you included when creating the request
    if event.metadata:
        print(f"Metadata: {event.metadata}")

    # Example: Check the decision for text-approval requests
    response = event.response or {}
    decision = response.get("decision")

    if decision == "approve":
        print("Action approved - executing...")
        # Add your approval logic here
    elif decision == "deny":
        print("Action denied - skipping...")
        # Add your denial logic here


def handle_opened(event):
    """Handle a request opened event."""
    print(f"Request {event.request_id} was opened by user")
    # Useful for tracking engagement


def handle_expired(event):
    """Handle a request expired event."""
    print(f"Request {event.request_id} expired")
    # Handle expiration (e.g., notify stakeholders, retry)


if __name__ == "__main__":
    if not WEBHOOK_SECRET:
        print("Warning: HAX_WEBHOOK_SECRET not set. Signature verification disabled.")

    print("Starting webhook server on http://localhost:8000")
    print("Webhook endpoint: http://localhost:8000/hax/webhook")
    uvicorn.run(app, host="0.0.0.0", port=8000)
