import pdfkit
from flask import current_app, render_template
from pathlib import Path
from app_server.models import Order

def render_invoice_to_pdf(order_id):
    # Fetch the order from the database
    order = Order.query.get_or_404(order_id)
    # Render the invoice HTML template with the order data
    html = render_template('web/invoice.html', order=order)

    # Full path to wkhtmltopdf (adjust if installed elsewhere)
    wk_path = r"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe"
    config = pdfkit.configuration(wkhtmltopdf=wk_path)

    # Build a temporary PDF path inside the app
    pdf_path = Path(current_app.root_path) / 'temp' / 'receipts' / f"receipt_{order.id}.pdf"
    pdf_path.parent.mkdir(parents=True, exist_ok=True)

    # Generate PDF from HTML string
    pdfkit.from_string(html, str(pdf_path), configuration=config)
    return pdf_path
