import asyncio
import logging
import os
import platform
from contextlib import asynccontextmanager

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

from api.main_router import api_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}")


@asynccontextmanager
async def lifespan(app: FastAPI):
    """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)")

        # Start Autonomous Curator Loop
        try:
            from agent.report_agent.autonomous_loop import ReportCurator
            curator = ReportCurator()
            asyncio.create_task(curator.start_loop())
            logger.info("✅ Report Curator Loop started (autonomous insights generator)")
        except ImportError as e:
            logger.warning(f"⚠️ Report Curator not available: {e}")

        # Start multi-job cron scheduler
        try:
            from agent.report_agent.scheduler import start_scheduler
            start_scheduler()
            logger.info("✅ Report Scheduler registered multi-job cron tasks")
        except ImportError as e:
            logger.warning(f"⚠️ Report Scheduler not available: {e}")

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

    yield

    """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 = FastAPI(
    title="Contract AI Service",
    description="API for Contract AI Service",
    version="1.0.0",
    lifespan=lifespan,
)


@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(api_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(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",
    )
