import os
import asyncio
import logging
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager

# Import Core
from core.container import DIContainer
from services import WebSocketManager, redis_client, redis_listener

# Import Routers
from routers import chat, quiz, multiplayer, curriculum, frontend, system

logger = logging.getLogger("uvicorn.error")

@asynccontextmanager
async def lifespan(app: FastAPI):
    print("Application starting up...")
    
    # 1. Initialize Container
    container = DIContainer()
    app.state.container = container 
    
    # 2. Initialize WebSocket Manager
    app.state.websocket_manager = WebSocketManager()
    print("DIContainer and WebSocketManager created.")

    # 3. Start Redis Listener
    if redis_client:
        print("Starting Redis Listener Task...")
        # Pass the manager stored in state
        listener_task = asyncio.create_task(redis_listener(app.state.websocket_manager))
        
        # Add a done callback to log immediate failures
        def handle_listener_failure(task):
            try:
                task.result()
            except asyncio.CancelledError:
                pass
            except Exception as e:
                logger.error(f"Redis Listener crashed: {e}", exc_info=True)

        listener_task.add_done_callback(handle_listener_failure)
        app.state.redis_listener_task = listener_task
    else:
        app.state.redis_listener_task = None
        print("WARNING: Redis not connected. Live Quiz feature will not work across multiple workers.")

    yield

    print("Application shutting down...")
    if app.state.redis_listener_task:
        app.state.redis_listener_task.cancel()
        try:
            await app.state.redis_listener_task
        except asyncio.CancelledError:
            pass
    
    if hasattr(app.state.container, 'agent_service'):
        app.state.container.agent_service.close() 
    print("Database connection pool closed.")

def create_app() -> FastAPI:
    app = FastAPI(title="Unified Chat API with Local Agent", lifespan=lifespan)
    
    # CORS Config
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"], 
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
        expose_headers=["X-Response-Text"],
    )

    @app.on_event("startup")
    async def startup_event():
        container = app.state.container
        print("MinIO Endpoint:", container.config.minio_endpoint)
        print("OpenAI Service Available:", container.openai_service.is_available())

    # Include Routers
    app.include_router(frontend.router)
    app.include_router(chat.router)
    app.include_router(quiz.router)     
    app.include_router(multiplayer.router) 
    app.include_router(curriculum.router)
    app.include_router(system.router)   

    return app

app = create_app()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app", 
        host="0.0.0.0", 
        port=int(os.environ.get("PORT", 8000)),
        reload=True
    )