from fastapi import FastAPI, UploadFile, File
from fastapi.responses import FileResponse
import os
import subprocess
import sys

app = FastAPI()

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

@app.get("/")
def health():
    return {"status": "ok"}

@app.post("/gerar-relatorio")
def gerar_relatorio(pdf: UploadFile = File(...)):
    entrada = os.path.join(BASE_DIR, "entrada.pdf")
    saida = os.path.join(BASE_DIR, "saida_organizada.pdf")

    with open(entrada, "wb") as f:
        f.write(pdf.file.read())

    subprocess.run(
        [sys.executable, "gerar_presencas.py"],
        cwd=BASE_DIR,
        check=True
    )

    if not os.path.exists(saida):
        return {"error": "PDF nao foi gerado"}

    return FileResponse(
        saida,
        media_type="application/pdf",
        filename="Relatorio_Presencas.pdf"
    )
