# services/pdf_agent.py
import os
import uuid
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas

TEMP_PDF_DIR = "temp_pdfs"


class PdfAgent:
    """Generate simple A4 PDFs from plain text."""

    def __init__(self):
        os.makedirs(TEMP_PDF_DIR, exist_ok=True)

    def generate_pdf(self, title: str, content: str) -> dict:
        file_id = f"{uuid.uuid4()}.pdf"
        path = os.path.join(TEMP_PDF_DIR, file_id)

        can = canvas.Canvas(path, pagesize=A4)
        width, height = A4

        # title
        can.setFont("Helvetica-Bold", 14)
        can.drawString(40, height - 60, title)

        # body
        can.setFont("Helvetica", 11)
        y = height - 100
        for line in content.splitlines():
            if y < 60:          # new page
                can.showPage()
                y = height - 60
                can.setFont("Helvetica", 11)
            can.drawString(40, y, line)
            y -= 14

        can.save()
        return {
            "filepath": path,
            "filename": f"{title.replace(' ', '_')}.pdf",
            "message": f"your pdf '{title}' is ready."
        }