import asyncio
import os
import platform
import logging

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

from api.chatbot_route import router as chatbot_router
from api.conservation_route import router as conservation_router
from api.memos import router as memos_router
from api.prompt_route import router as prompt_router
from common.cache import redis_cache
from common.langfuse_client import get_langfuse_client
from common.middleware import middleware_manager
from config import PORT
from memos_core.db import init_memo_db


# Windows event loop handling
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__)

langfuse_client = get_langfuse_client()
if langfuse_client:
    logger.info("Langfuse client ready (lazy loading)")
else:
    logger.warning("Langfuse client not available (missing keys or disabled)")

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


# =============================================================================
# STARTUP EVENT - Initialize Redis Cache + Memo DB
# =============================================================================
@app.on_event("startup")
async def startup_event():
    """Initialize dependencies on startup."""
    await redis_cache.initialize()
    logger.info("Redis cache initialized for message limit")
    await init_memo_db()
    logger.info("Memo SQLite DB initialized")


# =============================================================================
# MIDDLEWARE SETUP - Gom Auth + RateLimit + CORS vào một chỗ
# =============================================================================
middleware_manager.setup(
    app,
    enable_auth=True,        # bật/tắt Auth
    enable_rate_limit=False,  # tắt slowapi business rate limit
    enable_cors=True,         # bật CORS
    cors_origins=["*"],       # trong prod nên giới hạn origins
)

app.include_router(conservation_router)
app.include_router(chatbot_router)
app.include_router(prompt_router)
app.include_router(memos_router)


# --- MOCK API FOR LOAD TESTING ---
try:
    from api.mock_api_route import router as mock_router

    app.include_router(mock_router)
    print("Mock API Router mounted at /mock")
except ImportError:
    print("Mock Router not found, skipping...")

# ==========================================
# Mount static HTML
# ==========================================
try:
    static_dir = os.path.join(os.path.dirname(__file__), "static")
    if not os.path.exists(static_dir):
        os.makedirs(static_dir)
    app.mount("/static", StaticFiles(directory=static_dir, html=True), name="static")
    print(f"Static files mounted at /static (Dir: {static_dir})")
except Exception as e:
    print(f"Failed to mount static files: {e}")


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


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",
    )
