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.common.chatbot_route import router as chatbot_router
from api.history.check_history_route import router as check_history_router
from api.history.conservation_route import router as conservation_router
from api.common.mock_api_route import router as mock_router
from api.common.prompt_route import router as prompt_router
from api.product.stock_route import router as stock_router
from api.common.tool_prompt_route import router as tool_prompt_router
from api.common.n8n_api_route import router as n8n_router
from api.common.feedback_route import router as feedback_router
from api.api_sql.text_to_sql_route import router as text_to_sql_router
from api.common.dashboard_route import router as dashboard_router
from api.experiment_log.experiment_links_route import router as experiment_links_router
from api.product.product_route import router as product_router
from api.api_sql.sql_chat_route import router as sql_chat_router
from api.store_search.ai_store_search import router as ai_store_search_router
from api.image_search.ai_image_search import router as ai_image_search_router
from api.cache.cache_route import router as cache_router
from api.ai_report.report_html_route import router as report_html_router
from api.api_sql.ai_sql_trace_route import router as ai_sql_trace_router
from api.live_monitor.live_monitor_route import router as live_monitor_router
from api.prompt_optimizer.prompt_optimizer_route import router as prompt_optimizer_router
from api.user_simulator.user_simulator_route import router as user_simulator_router
from api.regression_test.regression_test_route import router as regression_test_router
from api.stress_test.stress_test_route import router as stress_test_router
from api.roadmap.roadmap_flow_route import router as roadmap_flow_router
from api.experiment_log.experiment_log_route import router as experiment_log_router
from api.common.auth_route import router as auth_router
from api.product_desc.product_desc_route import router as product_desc_router
from api.fashion_matches.router import router as fashion_matches_router
from api.fashion_matches.simulator import router as fashion_matches_simulator_router
from api.product_desc.bulk_ops_route import router as bulk_ops_router
from api.api_sql.user_insight_route import router as user_insight_router
from api.reaction_simulator.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)")

        # Thêm worker chạy ngầm tự động đồng bộ Tồn Kho Cache
        from api.stock_cache.stock_cache_route import stock_cache_worker_loop
        asyncio.create_task(stock_cache_worker_loop())
        logger.info("✅ Stock Cache Cron Job started (background task - 3 mins/sync)")


@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:
        return RedirectResponse(url="/home/index.html")
    
    if file_path == "index.html":
        file_path = "index.html" # just ensuring normal flow down to checking file

    # 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(fashion_matches_simulator_router)  # Realtime Fashion Simulator
app.include_router(bulk_ops_router)  # Bulk Search & Edit
from api.limit.limit_route import router as limit_router
app.include_router(limit_router)
from api.sku_search.ai_answer_sku import router as sku_search_router
app.include_router(sku_search_router)  # SKU Search Agent
from api.tag_search.ai_tag_search import router as tag_search_router
app.include_router(tag_search_router)  # Tag Search Agent
from api.lead_flow.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.product.canifa_product_api import router as canifa_product_router
app.include_router(canifa_product_router)  # Canifa Product Proxy (GraphQL)
from api.diagram_agent.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_fe.mock_auth_route import router as mock_auth_router
app.include_router(mock_auth_router)  # Mock Auth (identity linking test)

from api.feedback_agent.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)

from api.stock_cache.stock_cache_route import router as stock_cache_router
app.include_router(stock_cache_router) # API Cache Tồn Kho Redis Crawler

from api.social_inbox.social_inbox_route import router as social_inbox_router
app.include_router(social_inbox_router)  # Social Inbox (Facebook/Instagram/TikTok → Learning Loop)

# ─── Phase 2: AI Content Pipeline ───────────────────────────────────────────
from api.common.notification_route import router as notification_router
app.include_router(notification_router)  # In-app + Email + Webhook + Slack notifications

from api.content_approval.content_approval_route import router as content_approval_router
app.include_router(content_approval_router)  # Content approval gate (draft → review → publish)

from api.common.queue_route import router as queue_router
app.include_router(queue_router)  # Post queue + Calendar scheduling

from api.media_library.media_route import router as media_router
app.include_router(media_router)  # Media library (upload/resize/serve)

from api.content_approval.templates_route import router as templates_router
app.include_router(templates_router)  # Content templates + RSS feeds (ported from BrightBean)

# ─── Start publish engine background loop ───────────────────────────────────
from common.social.scheduler import start_publish_engine
start_publish_engine(app)  # Auto-publish scheduled content every 30s


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(f"📦 Stock Cache:      http://localhost:{PORT}/static/ton-cache.html")
    print(f"📋 Approval:         http://localhost:{PORT}/static/content-approval/index.html")
    print(f"📅 Calendar:         http://localhost:{PORT}/static/content-calendar/index.html")
    print(f"🖼️  Media Library:    http://localhost:{PORT}/static/media-library/index.html")
    print(f"📬 Social Inbox:     http://localhost:{PORT}/static/social-inbox/index.html")
    print(f"✍️  Composer:        http://localhost:{PORT}/static/content-composer/index.html")
    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",
    )
