from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from starlette.middleware.cors import CORSMiddleware
from pathlib import Path

from app.api.api import api_router
from contextlib import asynccontextmanager

from app.core.config import settings
from app.core.db import init_db
from app.initial_data import init_data

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Initialize DB
    await init_db()
    # Initialize Data
    await init_data()
    # Debug CORS
    print(f"Loaded CORS Origins: {settings.BACKEND_CORS_ORIGINS}")
    yield

app = FastAPI(
    title=settings.PROJECT_NAME,
    openapi_url=f"{settings.API_V1_STR}/openapi.json",
    lifespan=lifespan
)

# Set all CORS enabled origins
if settings.BACKEND_CORS_ORIGINS:
    app.add_middleware(
        CORSMiddleware,
        allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

# Mount static files
static_path = Path("static")
static_path.mkdir(exist_ok=True)
app.mount("/static", StaticFiles(directory="static"), name="static")

# Mount uploads
# Use configured upload directory from settings
uploads_path = Path(settings.UPLOAD_DIR)
uploads_path.mkdir(parents=True, exist_ok=True)

# Determine mount path based on config or convention
# For now we stick to /uploads as the URL prefix, but the directory is configurable
# If user wants a different URL prefix, we might need more config.
# Assuming /uploads prefix maps to settings.UPLOAD_DIR
app.mount("/uploads", StaticFiles(directory=settings.UPLOAD_DIR), name="uploads")

app.include_router(api_router, prefix=settings.API_V1_STR)
