from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import Response
from slugify import slugify
from sqlalchemy.orm import Session

from app.database import UPLOAD_DIR, get_db
from app.models import Recipe
from app.pdf.render import PdfRenderError, compile_recipe_pdf

router = APIRouter(prefix="/api/recipes", tags=["pdf"])


@router.get("/{recipe_id}/pdf")
def download_recipe_pdf(recipe_id: int, db: Session = Depends(get_db)):
    recipe = db.get(Recipe, recipe_id)
    if recipe is None:
        raise HTTPException(status_code=404, detail="Recipe not found")

    try:
        pdf_bytes = compile_recipe_pdf(recipe, UPLOAD_DIR)
    except PdfRenderError as exc:
        raise HTTPException(
            status_code=500,
            detail=f"{exc}: {exc.log_tail}",
        ) from exc

    filename = f"{slugify(recipe.name) or 'recipe'}.pdf"
    return Response(
        content=pdf_bytes,
        media_type="application/pdf",
        headers={"Content-Disposition": f'attachment; filename="{filename}"'},
    )
