"""
Demo Session Service - Main Application
Manages isolated demo sessions with ephemeral data
"""

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

from app.core import settings, DatabaseManager
from app.api import demo_sessions, demo_accounts, demo_operations
from shared.redis_utils import initialize_redis, close_redis

logger = structlog.get_logger()

# Initialize database
db_manager = DatabaseManager()


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan handler"""
    logger.info("Starting Demo Session Service", version=settings.VERSION)

    # Initialize database
    db_manager.initialize()

    # Initialize Redis using shared implementation
    await initialize_redis(
        redis_url=settings.REDIS_URL,
        db=0,
        max_connections=50
    )

    logger.info("Demo Session Service started successfully")

    yield

    # Cleanup on shutdown
    await db_manager.close()
    await close_redis()

    logger.info("Demo Session Service stopped")


app = FastAPI(
    title="Demo Session Service",
    description="Manages isolated demo sessions for prospect users",
    version=settings.VERSION,
    lifespan=lifespan
)

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


@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    """Global exception handler"""
    logger.error(
        "Unhandled exception",
        path=request.url.path,
        method=request.method,
        error=str(exc)
    )
    return JSONResponse(
        status_code=500,
        content={"detail": "Internal server error"}
    )


# Include routers
app.include_router(demo_sessions.router)
app.include_router(demo_accounts.router)
app.include_router(demo_operations.router)


@app.get("/")
async def root():
    """Root endpoint"""
    return {
        "service": "demo-session",
        "version": settings.VERSION,
        "status": "running"
    }


@app.get("/health")
async def health():
    """Health check endpoint"""
    from shared.redis_utils import get_redis_manager

    redis_manager = await get_redis_manager()
    redis_ok = await redis_manager.health_check()

    return {
        "status": "healthy" if redis_ok else "degraded",
        "service": "demo-session",
        "version": settings.VERSION,
        "redis": "connected" if redis_ok else "disconnected"
    }


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