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

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

# 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

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

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