"""
FastAPI main application - Contract AI Service

Architecture:
- REST API Routes: FastAPI routers for HTTP endpoints
- SSE (Server-Sent Events): Real-time streaming for AI Contract and AI Legal

Modules:
- ai_contract: Contract generation and composition (SSE streaming)
- ai_legal: Legal Q&A and search (SSE streaming)
- conversation: Conversation history management
"""

import os
import logging

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

from config import LANGSMITH_API_KEY, LANGSMITH_ENDPOINT, LANGSMITH_PROJECT, LANGSMITH_TRACING

# Ensure LangSmith Env Vars are set for the process
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


import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles  # Import StaticFiles

# from api.recommend_image import router as recommend_image_router
from api.recommend_text import router as recommend_text_router

from common.middleware import ClerkAuthMiddleware
from config import PORT

app = FastAPI(
    title="Contract AI Service",
    description="API for Contract AI Service",
    version="1.0.0",
)

print("✅ Clerk Authentication middleware DISABLED (for testing)")

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

# app.include_router(recommend_image_router)
app.include_router(recommend_text_router)

try:
    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")
    print(f"✅ Static files mounted at /static (Dir: {static_dir})")
except Exception as e:
    print(f"⚠️ Failed to mount static files: {e}")

from fastapi.responses import RedirectResponse

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

if __name__ == "__main__":
    print("=" * 60)
    print("🚀 Contract AI Service Starting...")
    print("=" * 60)
    print(f"📡 REST API: http://localhost:{PORT}")
    print(f"📡 SSE Streaming: http://localhost:{PORT}/api/ai-contract/chat")
    print(f"📡 Test Chatbot: http://localhost:{PORT}/static/index.html")
    print(f"📚 API Docs: http://localhost:{PORT}/docs")
    print("=" * 60)

    # ENABLE_RELOAD = os.getenv("ENABLE_RELOAD", "false").lower() in ("true", "1", "yes")
    ENABLE_RELOAD = True
    print("⚠️  Hot reload: FORCED ON (Dev Mode)")
    
    reload_dirs = [
        "ai_contract",
        "conversation",
        "common",
        "api", # Watch api folder
        "agent" # Watch agent folder
    ]

    uvicorn.run(
        "server:app",
        host="0.0.0.0",
        port=PORT,
        reload=ENABLE_RELOAD,
        reload_dirs=reload_dirs,
        log_level="info",
    )
