"""
AI Chatbot Service - Main Application
"""
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import logging

from app.config import settings
from app.api import routes, webhooks, webhook_routes, bulk_routes, export_routes, oauth_routes, upload_routes, admin_routes, client_portal_routes
from app.api.v2 import routes as v2_routes
from app.api.versioning import API_VERSION_DOCS
from app.api.graphql_api import graphql_router
from app.database import engine, Base
from app.middleware.rate_limiter import RateLimitMiddleware

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan events"""
    # Startup
    logger.info("Starting AI Chatbot Service...")
    # Create database tables
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    logger.info("Database tables created/verified")

    yield

    # Shutdown
    logger.info("Shutting down AI Chatbot Service...")


# Create FastAPI app
app = FastAPI(
    title="AI Chatbot Service",
    description="Enterprise AI Chatbot & Virtual Assistant Platform",
    version="1.0.0",
    lifespan=lifespan
)

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins_list,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Rate limiting middleware
app.add_middleware(
    RateLimitMiddleware,
    requests_per_minute=settings.RATE_LIMIT_PER_MINUTE,
    requests_per_hour=settings.RATE_LIMIT_PER_HOUR,
    burst_size=settings.RATE_LIMIT_BURST,
    exclude_paths=["/", "/health", "/docs", "/redoc", "/openapi.json", "/api/versions"],
    use_redis=False  # Set to True in production with Redis
)

# Include routers - API v1
app.include_router(routes.router, prefix="/api/v1/chat", tags=["Chat"])
app.include_router(webhooks.router, prefix="/api/v1/webhooks", tags=["Webhooks"])
app.include_router(webhook_routes.router, prefix="/api/v1/client-webhooks", tags=["Client Webhooks"])
app.include_router(bulk_routes.router, prefix="/api/v1/bulk", tags=["Bulk Operations"])
app.include_router(export_routes.router, prefix="/api/v1/export", tags=["Export"])
app.include_router(oauth_routes.router, prefix="/api/v1/auth/oauth", tags=["OAuth"])
app.include_router(upload_routes.router, prefix="/api/v1/files", tags=["File Upload"])
app.include_router(admin_routes.router, prefix="/api/v1/admin", tags=["Admin Portal"])
app.include_router(client_portal_routes.router, prefix="/api/v1/client", tags=["Client Portal"])

# Include routers - API v2
app.include_router(v2_routes.router, prefix="/api/v2", tags=["API v2"])

# GraphQL endpoint
app.include_router(graphql_router, prefix="/api/v2/graphql", tags=["GraphQL"])


@app.get("/api/versions")
async def list_api_versions():
    """List all available API versions with their status"""
    return {
        "versions": API_VERSION_DOCS,
        "current": "v1",
        "latest": "v1"
    }


@app.get("/")
async def root():
    """Health check endpoint"""
    return {
        "service": "AI Chatbot Service",
        "status": "running",
        "version": "1.0.0"
    }


@app.get("/health")
async def health_check():
    """Detailed health check"""
    return {
        "status": "healthy",
        "database": "connected",
        "ai_service": "ready"
    }


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "app.main:app",
        host="0.0.0.0",
        port=8000,
        reload=settings.DEBUG
    )
