"""
Main FastAPI application for AI Feedback Processing Service.
"""

from contextlib import asynccontextmanager

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

from app.api.v1.api import api_router
from app.core.database import close_db, init_db
from app.core.logging import get_logger
from app.middleware.sentry_middleware import SentryMiddleware
from app.services.sentry_service import SentryService

logger = get_logger("main")


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan manager."""
    # Startup
    logger.info("🚀 Starting AI Feedback FastAPI service...")

    # Initialize Sentry
    try:
        SentryService.init_sentry()
        logger.info("✅ Sentry initialized successfully")
    except Exception as e:
        logger.warning(f"⚠️  Sentry initialization warning: {e}")

    # Initialize database
    try:
        await init_db()
        logger.info("✅ Database initialized successfully")
    except Exception as e:
        logger.error(f"❌ Database initialization failed: {e}")
        raise

    # Start background tasks
    try:
        from app.services.background_tasks import BackgroundTaskService

        background_service = BackgroundTaskService()
        await background_service.start_timeout_monitoring()
        logger.info("✅ Background tasks started successfully")
        app.state.background_service = background_service
    except Exception as e:
        logger.warning(f"⚠️  Background tasks startup warning: {e}")

    yield

    # Shutdown
    logger.info("🛑 Shutting down AI Feedback FastAPI service...")

    # Stop background tasks
    try:
        if hasattr(app.state, "background_service"):
            await app.state.background_service.stop_timeout_monitoring()
            logger.info("✅ Background tasks stopped successfully")
    except Exception as e:
        logger.warning(f"⚠️  Background tasks shutdown warning: {e}")

    # Close database connections
    await close_db()
    logger.info("✅ Database connections closed")


# Create FastAPI app
app = FastAPI(
    title="AI Feedback Processing Service",
    description="FastAPI service for processing AI feedback on video interviews",
    version="2.0.0",
    lifespan=lifespan,
)

# Add Sentry middleware first (for performance monitoring)
app.add_middleware(SentryMiddleware)

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Configure this properly for production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Include API router
app.include_router(api_router, prefix="/api/v1")


# Global exception handler
@app.exception_handler(Exception)
async def global_exception_handler(_request: Request, exc: Exception):
    """Global exception handler."""
    logger.error(f"Unhandled exception: {exc}")

    # Capture exception in Sentry
    try:
        SentryService.capture_exception(exc)
    except Exception as sentry_error:
        logger.warning(f"Failed to capture exception in Sentry: {sentry_error}")

    return JSONResponse(
        status_code=500,
        content={"detail": "Internal server error"},
    )


# Health check endpoint
@app.get("/health")
async def health_check():
    """Health check endpoint."""
    try:
        from app.services.health import HealthService

        health_service = HealthService()
        health_status = await health_service.check_all()
        return health_status
    except Exception as e:
        logger.error(f"Health check failed: {e}")
        return {"status": "unhealthy", "error": str(e)}


# Root endpoint
@app.get("/")
async def root():
    """Root endpoint."""
    return {
        "message": "AI Feedback Processing Service",
        "version": "2.0.0",
        "docs": "/docs",
        "health": "/health",
    }
