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.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.ai_store_search import router as ai_store_search_router
from api.ai_image_search import router as ai_image_search_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 api.fashion_matches_route import router as fashion_matches_router
from api.bulk_ops_route import router as bulk_ops_router
from api.user_insight_route import router as user_insight_router
from api.reaction_simulator_route import router as reaction_simulator_router
from common.cache import redis_cache
from common.event_bus import event_bus
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, EventBus, and start background workers."""
    await redis_cache.initialize()
    logger.info("✅ Redis cache initialized")

    # Start FastStream EventBus
    await event_bus.start()

   # Cleaned up Note APIs
    # 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.on_event("shutdown")
async def shutdown_event():
    """Cleanup resources before exit to prevent connection leaks during hot-reload."""
    # Stop FastStream EventBus
    await event_bus.stop()

    from common.db_pool import db_pool
    if db_pool:
        db_pool.close_all()
        logger.info("🛑 Postgres Connection Pool nicely closed")

    # Optional: If you want to also clean up StarRocks you can do it here
    try:
        from common.starrocks_connection import StarRocksConnection
        if StarRocksConnection._shared_conn and StarRocksConnection._shared_conn.open:
            StarRocksConnection._shared_conn.close()
            logger.info("🛑 StarRocks Connection nicely closed")
    except Exception:
        pass


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

@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)

@app.get("/home/{file_path:path}")
async def serve_home_static(file_path: str):
    """Serve home dashboard explicitly under /home namespace."""
    if not file_path or file_path == "index.html":
        return RedirectResponse(url="/home/index.html")
    
    # Check if the file exists under static/home
    home_path = os.path.join(STATIC_DIR, "home", file_path)
    if os.path.isfile(home_path):
        return FileResponse(home_path)
        
    # Fallback to standard static if not found (for common assets like css/js)
    common_path = os.path.join(STATIC_DIR, file_path)
    if os.path.isfile(common_path):
        return FileResponse(common_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(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(ai_store_search_router)  # AI Store Search
app.include_router(ai_image_search_router)  # AI Image Search
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
app.include_router(fashion_matches_router)  # Fashion Matches (AI Stylist Engine)
app.include_router(bulk_ops_router)  # Bulk Search & Edit
from api.limit_route import router as limit_router
app.include_router(limit_router)
from api.ai_answer_sku import router as sku_search_router
app.include_router(sku_search_router)  # SKU Search Agent
from api.ai_tag_search import router as tag_search_router
app.include_router(tag_search_router)  # Tag Search Agent
from api.lead_flow_route import router as lead_flow_router
app.include_router(lead_flow_router)  # Lead Stage AI (Experiment)
app.include_router(user_insight_router)  # User Insight Dashboard
app.include_router(reaction_simulator_router)  # Reaction Simulator
from api.canifa_product_api import router as canifa_product_router
app.include_router(canifa_product_router)  # Canifa Product Proxy (GraphQL)
from api.ai_diagram_route import router as diagram_router
app.include_router(diagram_router)  # AI Diagram Agent
from api.merge_history.merge_history_route import router as merge_history_router
app.include_router(merge_history_router)  # Mock merge history endpoints
from api.mock_auth_route import router as mock_auth_router
app.include_router(mock_auth_router)  # Mock Auth (identity linking test)

from api.feedback_agent_route import router as feedback_agent_router
app.include_router(feedback_agent_router) # Lõi Agent Rút Kinh Nghiệm (Langfuse -> Rules)


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