"""
FastAPI Restaurant Website Generator
Main application entry point
"""

from fastapi import FastAPI, Response, Request
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from contextlib import asynccontextmanager
import os
from pathlib import Path
import logging

logger = logging.getLogger(__name__)

# Import settings for LangSmith setup
from core.config import settings

# LangSmith tracing setup (global initialization)
if settings.langsmith_api_key:
    os.environ["LANGSMITH_API_KEY"] = settings.langsmith_api_key
    os.environ["LANGSMITH_PROJECT"] = settings.langsmith_project
    os.environ["LANGCHAIN_TRACING_V2"] = "true"
    os.environ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com"
    print(f"🔧 LangSmith tracing enabled for project: {settings.langsmith_project}")
else:
    print("⚠️ LangSmith API key not set - tracing disabled")

# Import API routers
from api.website import router as website_router
from api.files import router as files_router
from api.preview import router as preview_router


@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    Lifespan context manager for FastAPI application.
    Handles startup and shutdown events.
    """
    # Startup
    from middleware.mysql_logging import start_logging_system
    from utils.db import _create_connection_pool
    
    # Initialize database connection pool with graceful error handling
    try:
        await _create_connection_pool()
        print("✅ Database connection pool initialized")
    except Exception as e:
        logger.error(f"⚠️ Failed to initialize database connection pool: {e}")
        logger.warning("Application will start without database logging. Please check MySQL credentials.")
    
    # Start async logging system (gracefully handles missing DB connection)
    try:
        await start_logging_system()
        print("✅ Async logging system started")
    except Exception as e:
        logger.error(f"⚠️ Failed to start logging system: {e}")
        logger.warning("Application will continue without API logging")
    
    yield  # Application runs
    
    # Shutdown
    from middleware.mysql_logging import stop_logging_system
    from utils.db import close_pool
    
    # Stop logging system (flushes remaining logs)
    try:
        await stop_logging_system()
        print("✅ Async logging system stopped")
    except Exception as e:
        logger.error(f"Error stopping logging system: {e}")
    
    # Close database connection pool
    try:
        await close_pool()
        print("✅ Database connection pool closed")
    except Exception as e:
        logger.error(f"Error closing connection pool: {e}")


# Create FastAPI app with lifespan
app = FastAPI(
    title="Restaurant Website Generator",
    description="AI-powered restaurant website generation with DeepSite integration",
    version="2.0.0",
    lifespan=lifespan
)

# MySQL request logging middleware
from middleware.mysql_logging import mysql_logging_middleware

@app.middleware("http")
async def add_mysql_logging(request: Request, call_next):
    return await mysql_logging_middleware(request, call_next)


# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.allowed_origins,  # Configure appropriately for production via env
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Health check endpoint (before static files)
@app.get("/health")
async def health_check():
    return {"status": "healthy", "version": "2.0.0"}

# Cache control for JavaScript files
@app.get("/js/{file_path:path}")
async def serve_js(file_path: str):
    """Serve JavaScript files with no-cache headers"""
    public_path = Path(__file__).parent.parent / "public"
    file_location = public_path / "js" / file_path
    
    if not file_location.exists() or not file_location.is_file():
        return Response(status_code=404)
    
    response = FileResponse(
        path=str(file_location),
        media_type="application/javascript"
    )
    
    # Set cache control headers
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "0"
    
    return response

# Cache control for CSS files
@app.get("/styles.css")
async def serve_css():
    """Serve CSS file with no-cache headers"""
    public_path = Path(__file__).parent.parent / "public"
    file_location = public_path / "styles.css"
    
    if not file_location.exists():
        return Response(status_code=404)
    
    response = FileResponse(
        path=str(file_location),
        media_type="text/css"
    )
    
    # Set cache control headers
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "0"
    
    return response

# Include API routers
app.include_router(website_router, prefix="/api", tags=["website"])
app.include_router(files_router, prefix="/api", tags=["files"])
app.include_router(preview_router, prefix="/api", tags=["preview"])

# Mount static files (after API routes)
public_path = Path(__file__).parent.parent / "public"
if public_path.exists():
    app.mount("/", StaticFiles(directory=str(public_path), html=True), name="static")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host=settings.get_current_domain().split("://")[1].split(":")[0], port=settings.app_port)
