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.check_history_route import router as check_history_router
from api.conservation_route import router as conservation_router
from api.stock_route import router as stock_router
from api.test_conversation_route import router as test_conversation_router
from common.cache import redis_cache
from common.middleware import middleware_manager
from config import PORT

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

# 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"✅ 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 on startup."""
    await redis_cache.initialize()
    logger.info("✅ Redis cache initialized")


@app.get("/")
async def root():
    return RedirectResponse(url="/static/test_conversation.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:
        file_path = "index.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=True,
    enable_rate_limit=True,
    enable_cors=True,
    cors_origins=["*"],
)


# api include
app.include_router(conservation_router)
app.include_router(check_history_router)
app.include_router(stock_router)
app.include_router(test_conversation_router)


if __name__ == "__main__":
    print("=" * 60)
    print("🚀 Contract AI Service Starting...")
    print("=" * 60)
    print(f"📡 REST API: http://localhost:{PORT}")
    print(f"📡 Test Tool: http://localhost:{PORT}/static/test_conversation.html")
    print(f"📚 API Docs: http://localhost:{PORT}/docs")
    print("=" * 60)

    ENABLE_RELOAD = False
    print(f"⚠️  Hot reload: {ENABLE_RELOAD}")

    reload_dirs = ["common", "api"]

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