import asyncio
import logging
import os
import platform

import uvicorn
from fastapi import FastAPI
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles

from api.chatbot_route import router as chatbot_router
from api.check_history_route import router as check_history_router
from api.conservation_route import router as conservation_router
from api.mock_api_route import router as mock_router
from api.prompt_route import router as prompt_router
from api.stock_route import router as stock_router
from api.tool_prompt_route import router as tool_prompt_router
from api.n8n_api_route import router as n8n_router
from common.cache import redis_cache
from common.middleware import middleware_manager
from config import PORT

if platform.system() == "Windows":
    print("🔧 Windows detected: Applying SelectorEventLoopPolicy globally...")
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

# Configure Logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
    handlers=[logging.StreamHandler()],
)

logger = logging.getLogger(__name__)

# Static files directory
STATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
if not os.path.exists(STATIC_DIR):
    os.makedirs(STATIC_DIR)
print(f"✅ Static dir resolved: {STATIC_DIR}")


app = FastAPI(
    title="Contract AI Service",
    description="API for Contract AI Service",
    version="1.0.0",
)


@app.on_event("startup")
async def startup_event():
    """Initialize Redis cache on startup."""
    await redis_cache.initialize()
    logger.info("✅ Redis cache initialized")


@app.on_event("shutdown")
async def shutdown_event():
    """Gracefully close database connection pools on shutdown to prevent connection leaks during hot-reloads."""
    try:
        from common.conversation_manager import get_conversation_manager
        manager = await get_conversation_manager()
        await manager.close()
        logger.info("✅ Postgres connection pool closed gracefully")
    except Exception as e:
        logger.error(f"Error closing Postgres pool: {e}")

    try:
        from common.starrocks_connection import StarRocksConnection
        await StarRocksConnection.clear_pool()
        logger.info("✅ StarRocks connection pool closed gracefully")
    except Exception as e:
        logger.error(f"Error closing StarRocks pool: {e}")


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


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


@app.get("/static/{file_path:path}")
async def serve_static(file_path: str):
    """Serve static files explicitly to avoid middleware conflict."""
    if not file_path:
        file_path = "index.html"
    full_path = os.path.join(STATIC_DIR, file_path)
    if os.path.isfile(full_path):
        return FileResponse(full_path)
    return JSONResponse({"detail": "Not Found"}, status_code=404)


# =====================================================================
# MIDDLEWARE (after static mount)
# =====================================================================
middleware_manager.setup(
    app,
    enable_auth=True,
    enable_rate_limit=True,
    enable_cors=True,
    cors_origins=["*"],
)


# api include
app.include_router(conservation_router)
app.include_router(check_history_router)
app.include_router(chatbot_router)
app.include_router(prompt_router)
app.include_router(tool_prompt_router)  # Register new router
app.include_router(mock_router)
app.include_router(stock_router)
app.include_router(n8n_router)


if __name__ == "__main__":
    print("=" * 60)
    print("🚀 Contract AI Service Starting...")
    print("=" * 60)
    print(f"📡 REST API: http://localhost:{PORT}")
    print(f"📡 Test Chatbot: http://localhost:{PORT}/static/index.html")
    print(f"📚 API Docs: http://localhost:{PORT}/docs")
    print("=" * 60)

    ENABLE_RELOAD = False
    print(f"⚠️  Hot reload: {ENABLE_RELOAD}")

    reload_dirs = ["common", "api", "agent"]

    if ENABLE_RELOAD:
        os.environ["PYTHONUNBUFFERED"] = "1"

    uvicorn.run(
        "server:app",
        host="0.0.0.0",
        port=PORT,
        reload=ENABLE_RELOAD,
        reload_dirs=reload_dirs,
        log_level="info",
        loop="asyncio" if platform.system() == "Windows" else "auto"
    )
