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 api.feedback_route import router as feedback_router
from api.text_to_sql_route import router as text_to_sql_router
from api.dashboard_route import router as dashboard_router
from api.notes_route import router as notes_router
from api.experiment_links_route import router as experiment_links_router
from api.product_route import router as product_router
from api.sql_chat_route import router as sql_chat_router
from api.cache_route import router as cache_router
from api.report_html_route import router as report_html_router
from api.ai_sql_trace_route import router as ai_sql_trace_router
from api.live_monitor_route import router as live_monitor_router
from api.prompt_optimizer_route import router as prompt_optimizer_router
from api.user_simulator_route import router as user_simulator_router
from api.regression_test_route import router as regression_test_router
from api.stress_test_route import router as stress_test_router
from api.roadmap_flow_route import router as roadmap_flow_router
from api.experiment_log_route import router as experiment_log_router
from api.auth_route import router as auth_router
from api.product_desc_route import router as product_desc_router
from common.cache import redis_cache
from common.middleware import middleware_manager
from config import PORT, REDIS_CACHE_TURN_ON


if platform.system() == "Windows":
    print("[WINDOWS] 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"[OK] 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 and start background workers."""
    await redis_cache.initialize()
    logger.info("✅ Redis cache initialized")

    # Start report worker if Redis is available
    if REDIS_CACHE_TURN_ON and redis_cache.get_client():
        from agent.report_agent.report_queue import report_worker_loop
        asyncio.create_task(report_worker_loop())
        logger.info("✅ Report Queue Worker started (background task)")


@app.get("/")
async def root():
    return RedirectResponse(url="/static/main.html?page=roadmap.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 or file_path == "index.html":
        return RedirectResponse(url="/static/main.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=False,
    enable_rate_limit=False,
    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)
app.include_router(feedback_router)
app.include_router(text_to_sql_router)  # Bản 2: Text-to-SQL
app.include_router(dashboard_router)  # Dashboard overview
app.include_router(notes_router)  # Dashboard team notes
app.include_router(experiment_links_router)  # Experiment links sidebar
app.include_router(product_router)  # Product performance dashboard
app.include_router(sql_chat_router)  # AI Data Analyst (Text-to-SQL)
app.include_router(cache_router)  # Cache management dashboard
app.include_router(report_html_router)   # AI Report HTML Generator
app.include_router(ai_sql_trace_router)  # AI SQL Trace
app.include_router(live_monitor_router)  # Realtime live monitor
app.include_router(prompt_optimizer_router)  # Prompt Optimizer
app.include_router(user_simulator_router)  # User Simulator
app.include_router(regression_test_router)  # Regression Test
app.include_router(stress_test_router)  # Stress Test
app.include_router(roadmap_flow_router)  # Roadmap & Flow
app.include_router(experiment_log_router)  # Experiment Log
app.include_router(auth_router)  # Auth (login/me/logout)
app.include_router(product_desc_router)  # Ultra Description Manager
from api.limit_route import router as limit_router
app.include_router(limit_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",
    )
