
import asyncio
import os
import platform
import logging
from contextlib import asynccontextmanager

import uvicorn
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import RedirectResponse, ORJSONResponse

from api.chatbot import router as chatbot_router
from api.memos import router as memos_router
from api.auth_routes import router as auth_router
from api.test_chat_route import router as test_router
from api.team_routes import router as team_router
from api.inbound_webhook_routes import router as webhook_router
from api.documents.documents_routes import router as documents_router
from common.cache import redis_cache
from common.langfuse_client import get_langfuse_client
from common.meili_service import meili_service
from common.middleware import middleware_manager
from config import PORT, CORS_ORIGINS, DISABLE_AUTH


if platform.system() == "Windows":
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

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

@asynccontextmanager
async def lifespan(app: FastAPI):
    logger.info("🚀 Lifespan starting...")
    try:
        logger.info("🔧 Initializing Redis...")
        await redis_cache.initialize()
        logger.info("✅ Redis initialized")
        
        logger.info("🔧 Initializing SQLite...")
        from common.sqlite_client import init_sqlite
        await init_sqlite()
        logger.info("✅ SQLite initialized")
        
        logger.info("🔧 Initializing Meilisearch...")
        await meili_service.initialize()
        logger.info("✅ Meilisearch initialized")
    except Exception as e:
        logger.error(f"❌ Error during lifespan initialization: {e}")
        
    yield
    
    logger.info("🚀 Lifespan shutting down...")
    try:
        from common.sqlite_client import close_sqlite
        await close_sqlite()
        logger.info("✅ SQLite closed")
    except Exception as e:
        logger.error(f"❌ Error during lifespan shutdown: {e}")

app = FastAPI(title="CuCu Note API", lifespan=lifespan, default_response_class=ORJSONResponse)

middleware_manager.setup(app, enable_auth=True, enable_rate_limit=False, enable_cors=True, cors_origins=CORS_ORIGINS)

# Consolidate all /api/v1 routes
app.include_router(test_router, prefix="/api/test")
app.include_router(auth_router, prefix="/api/v1/auth")
app.include_router(chatbot_router, prefix="/api/agent")
app.include_router(memos_router, prefix="/api/v1")
app.include_router(team_router, prefix="/api/v1")
app.include_router(webhook_router, prefix="/api/v1")
app.include_router(documents_router, prefix="/api/v1")

@app.get("/health")
async def health(): return {"status": "ok"}

@app.get("/")
async def root(): return RedirectResponse(url="/static/index.html")

if __name__ == "__main__":
    logger.info(f"📍 Starting CuCu Note Backend on port {PORT}...")
    try:
        uvicorn.run("server:app", host="0.0.0.0", port=PORT, reload=True)
    except Exception as e:
        logger.error(f"❌ Failed to start server: {e}")
