"""Payment processing routes."""

from fastapi import APIRouter, HTTPException, Header
from pydantic import BaseModel, EmailStr
from typing import Optional, Dict, Any, Literal
from agenticlypay.payments import PaymentProcessor
from agenticlypay.utils.firestore_storage import FirestoreStorage

router = APIRouter()
payment_processor = PaymentProcessor()
storage = FirestoreStorage()


class ProcessPaymentRequest(BaseModel):
    """Request model for processing a payment."""

    protocol: Literal["AUTO"]
    amount: int  # in cents
    currency: str = "usd"
    developer_account_id: str
    email: EmailStr  # Required for usage tracking
    metadata: Optional[Dict[str, Any]] = None
    description: Optional[str] = None
    mandate: Optional[Dict[str, Any]] = None  # Required for AP2
    resource_url: Optional[str] = None  # Optional for x402


class ConfirmPaymentRequest(BaseModel):
    """Request model for confirming a payment."""

    protocol: Literal["AUTO"]
    payment_id: str
    payment_method: Optional[str] = None


@router.post("/process")
async def process_payment(request: ProcessPaymentRequest):
    """Process a payment using the specified protocol."""
    try:
        # Auto-detect protocol if requested
        protocol = request.protocol
        if protocol.upper() == "AUTO":
            if request.mandate is not None:
                protocol = "AP2"
            elif request.resource_url is not None:
                protocol = "x402"
            else:
                protocol = "ACP"

        result = payment_processor.process_payment(
            protocol=protocol,
            amount=request.amount,
            currency=request.currency,
            developer_account_id=request.developer_account_id,
            metadata=request.metadata,
            description=request.description,
            mandate=request.mandate,
            resource_url=request.resource_url,
        )
        
        # Log usage by email
        storage.log_usage(
            email=request.email,
            endpoint="POST /api/v1/payments/process",
            status_code=200,
        )
        
        return {"success": True, "payment": result}
    except ValueError as e:
        # Log error usage
        storage.log_usage(
            email=request.email,
            endpoint="POST /api/v1/payments/process",
            status_code=400,
        )
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        # Log error usage
        storage.log_usage(
            email=request.email,
            endpoint="POST /api/v1/payments/process",
            status_code=500,
        )
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/confirm")
async def confirm_payment(request: ConfirmPaymentRequest, x_developer_email: Optional[str] = Header(None, alias="X-Developer-Email")):
    """Confirm a payment."""
    try:
        # Get email from header
        email = x_developer_email
        if not email:
            raise HTTPException(status_code=400, detail="email is required in X-Developer-Email header")
        result = payment_processor.confirm_payment(
            email=email,
            protocol=request.protocol,
            payment_id=request.payment_id,
            payment_method=request.payment_method,
        )
        return {"success": True, "payment": result}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/status/{protocol}/{payment_id}")
async def get_payment_status(protocol: str, payment_id: str, email: Optional[str] = None, x_developer_email: Optional[str] = Header(None, alias="X-Developer-Email")):
    """Get payment status."""
    try:
        # Get email from query param or header
        email = email or x_developer_email
        if not email:
            raise HTTPException(status_code=400, detail="email is required (query param or X-Developer-Email header)")
        result = payment_processor.get_payment_status(
            email=email,
            protocol=protocol.upper(), 
            payment_id=payment_id
        )
        return {"success": True, "status": result}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/fee/{amount}")
async def calculate_fee(amount: int, email: Optional[str] = None, x_developer_email: Optional[str] = Header(None, alias="X-Developer-Email")):
    """Calculate platform fee for an amount."""
    try:
        # Get email from query param or header
        email = email or x_developer_email
        if not email:
            raise HTTPException(status_code=400, detail="email is required (query param or X-Developer-Email header)")
        result = payment_processor.calculate_fee(email=email, amount_cents=amount)
        return {"success": True, "fee": result}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

