"""FastAPI main application."""

import logging
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
from agenticlypay.config import config
from agenticlypay.api.routes import (
    connect,
    payments,
    payouts,
    tax,
    webhooks,
    console,
)
from agenticlypay.api.middleware.usage import usage_middleware

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)

# Rate limiter
limiter = Limiter(key_func=get_remote_address)

app = FastAPI(
    title="AgenticlyPay API",
    description="API for processing agentic payments (ACP, AP2, x402) via Stripe",
    version="0.7.0",
)

# Add rate limiter to app state
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

# CORS configuration - explicitly list allowed origins (no wildcard for security)
allowed_origins = [config.frontend_url]
# Add common development origins if in development mode
if config.frontend_url.startswith("http://localhost"):
    allowed_origins.extend([
        "http://localhost:3000",
        "http://127.0.0.1:3000",
    ])

app.add_middleware(
    CORSMiddleware,
    allow_origins=allowed_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Usage logging middleware (non-intrusive)
app.middleware("http")(usage_middleware)

# Include routers
app.include_router(connect.router, prefix="/api/v1/connect", tags=["Connect"])
app.include_router(payments.router, prefix="/api/v1/payments", tags=["Payments"])
app.include_router(payouts.router, prefix="/api/v1/payouts", tags=["Payouts"])
app.include_router(tax.router, prefix="/api/v1/tax", tags=["Tax"])
app.include_router(webhooks.router, prefix="/api/v1/webhooks", tags=["Webhooks"])
app.include_router(console.router, prefix="/api/v1/console", tags=["Console"])

# Square webhook endpoint at /api/v1/square (separate from webhooks router)
from agenticlypay.api.routes.webhooks import square_webhook
app.post("/api/v1/square", tags=["Webhooks"])(square_webhook)


@app.get("/")
async def root():
    """Root endpoint."""
    return {
        "service": "AgenticlyPay API",
        "version": "0.7.0",
        "status": "running",
    }


@app.get("/health")
async def health():
    """Health check endpoint with dependency verification."""
    health_status = {"status": "healthy", "checks": {}}
    
    # Check Firestore connection
    try:
        from agenticlypay.utils.firestore_storage import db
        # Simple connectivity check
        db.collection("_health_check").limit(1).get()
        health_status["checks"]["firestore"] = "connected"
    except Exception as e:
        health_status["checks"]["firestore"] = f"error: {str(e)}"
        health_status["status"] = "degraded"
    
    # Check Stripe configuration
    if config.stripe_secret_key:
        health_status["checks"]["stripe"] = "configured"
    else:
        health_status["checks"]["stripe"] = "not configured"
        health_status["status"] = "degraded"
    
    # Check Square configuration
    if config.square_access_token:
        health_status["checks"]["square"] = "configured"
    else:
        health_status["checks"]["square"] = "not configured"
    
    status_code = 200 if health_status["status"] == "healthy" else 503
    return JSONResponse(content=health_status, status_code=status_code)

