"""
FastAPI Server - Canifa Product Recommendation API
"""

import os
import logging

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import RedirectResponse

from config import (
    PORT,
    ENV_MODE,
    LANGSMITH_API_KEY,
    LANGSMITH_ENDPOINT,
    LANGSMITH_PROJECT,
    LANGSMITH_TRACING,
)
from api.recommend_text import router as recommend_text_router

# Logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
    handlers=[logging.StreamHandler()]
)
logger = logging.getLogger(__name__)

# LangSmith environment
os.environ["LANGSMITH_TRACING"] = LANGSMITH_TRACING
os.environ["LANGSMITH_ENDPOINT"] = LANGSMITH_ENDPOINT
os.environ["LANGSMITH_API_KEY"] = LANGSMITH_API_KEY
os.environ["LANGSMITH_PROJECT"] = LANGSMITH_PROJECT

# FastAPI app
app = FastAPI(
    title="Canifa Product Recommendation API",
    description="API for product recommendation using hybrid search",
    version="1.0.0",
)

# CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Routes
app.include_router(recommend_text_router)

# Static files
static_dir = os.path.join(os.path.dirname(__file__), "static")
if not os.path.exists(static_dir):
    os.makedirs(static_dir)
app.mount("/static", StaticFiles(directory=static_dir, html=True), name="static")


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


if __name__ == "__main__":
    import uvicorn
    
    is_dev = ENV_MODE != "prod"
    
    logger.info(f"Starting server on port {PORT} (ENV_MODE={ENV_MODE})")
    
    if is_dev:
        uvicorn.run(
            "server:app",
            host="0.0.0.0",
            port=PORT,
            reload=True,
            reload_dirs=["."],
            log_level="info",
        )
    else:
        uvicorn.run(
            "server:app",
            host="0.0.0.0",
            port=PORT,
            workers=os.cpu_count() * 2 + 1,
            log_level="info",
        )
