"""Webhook handlers for Stripe events."""

from fastapi import APIRouter, Request, HTTPException, Header
from typing import Optional
import json
from agenticlypay.stripe_client import StripeClient
from agenticlypay.payments import PaymentProcessor

router = APIRouter()
stripe_client = StripeClient()
payment_processor = PaymentProcessor()


@router.post("/stripe")
async def stripe_webhook(
    request: Request,
    stripe_signature: Optional[str] = Header(None, alias="stripe-signature"),
):
    """Handle Stripe webhook events."""
    if not stripe_signature:
        raise HTTPException(status_code=400, detail="Missing stripe-signature header")

    try:
        payload = await request.body()
        event = stripe_client.construct_webhook_event(
            payload=payload, sig_header=stripe_signature
        )

        # Handle the event
        event_data = event.to_dict()
        result = payment_processor.handle_webhook(event_data)

        return {"success": True, "handled": result.get("handled", False), "result": result}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=f"Invalid payload: {str(e)}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/wise")
async def wise_webhook(
    request: Request,
    x_signature: Optional[str] = Header(None, alias="X-Signature"),
):
    """Handle Wise webhook events."""
    try:
        payload = await request.json()
        
        # Verify webhook signature if webhook secret is configured
        from agenticlypay.config import config
        if config.wise_webhook_secret and x_signature:
            # Verify signature (Wise uses HMAC-SHA256)
            import hmac
            import hashlib
            import json
            
            payload_str = json.dumps(payload, sort_keys=True)
            expected_signature = hmac.new(
                config.wise_webhook_secret.encode(),
                payload_str.encode(),
                hashlib.sha256
            ).hexdigest()
            
            if not hmac.compare_digest(x_signature, expected_signature):
                raise HTTPException(status_code=401, detail="Invalid webhook signature")
        
        # Handle Wise webhook events
        event_type = payload.get("event_type") or payload.get("type")
        data = payload.get("data") or payload
        
        # Update payout status in Firestore when transfer status changes
        if event_type in ["transfers#state-change", "transfers#outgoing-payment-paid"]:
            transfer_id = data.get("resource_id") or data.get("transfer_id") or data.get("id")
            
            if transfer_id:
                from google.cloud import firestore
                db = firestore.Client()
                
                # Find payout record by transfer_id
                payouts_query = (
                    db.collection("wise_payouts")
                    .where("transfer_id", "==", str(transfer_id))
                    .limit(1)
                    .stream()
                )
                
                for doc in payouts_query:
                    new_status = data.get("current_state") or data.get("status") or "paid"
                    doc.reference.update({
                        "status": new_status,
                        "updated_at": firestore.SERVER_TIMESTAMP,
                    })
                    break
        
        return {"success": True, "event_type": event_type, "handled": True}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/test")
async def test_webhook():
    """Test webhook endpoint."""
    return {"status": "webhook endpoint is active"}

