"""FastAPI application factory."""

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse

from mixlift.auth.router import router as auth_router
from mixlift.billing.router import router as billing_router
from mixlift.config import ensure_directories, settings
from mixlift.ingest.router import router as ingest_router
from mixlift.modeling.router import router as modeling_router
from mixlift.projects.router import router as projects_router
from mixlift.results.router import router as results_router

ensure_directories()

app = FastAPI(
    title=settings.app_name,
    description="Open-source Marketing Mix Model tool",
    version="0.1.0",
)

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

# Register routers
app.include_router(auth_router)
app.include_router(projects_router)
app.include_router(ingest_router)
app.include_router(modeling_router)
app.include_router(results_router)
app.include_router(billing_router)


@app.get("/health")
async def health():
    return {"status": "ok", "version": "0.1.0"}


@app.get("/templates/{platform}")
async def download_template(platform: str):
    """Download a CSV template for a given ad platform."""
    from pathlib import Path

    templates_dir = Path(__file__).parent.parent / "templates"
    filename = f"{platform}_template.csv"
    filepath = templates_dir / filename

    if not filepath.exists():
        from fastapi import HTTPException

        raise HTTPException(status_code=404, detail=f"Template not found for '{platform}'")

    return FileResponse(filepath, filename=filename, media_type="text/csv")
