#!/usr/bin/env python3
import fitz  # PyMuPDF
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
import os


def generate_pdf(path="labels"):
    # Open the existing PDF
    image_folder_path = path
    doc = fitz.open('label_template.pdf')
    page = doc[0]  # Assuming you want to read from the first page

    placeholders = []
    for shape in page.get_drawings():
        if shape['type'] == 's':  # Checking for rectangle types
            placeholders.append({
                'x': shape['rect'].x0,
                'y': shape['rect'].y0,
                'width': shape['rect'].width,
                'height': shape['rect'].height
            })

    # List all PNG images in the folder
    image_files = [f for f in os.listdir(image_folder_path) if f.endswith('.png')]
    image_paths = [os.path.join(image_folder_path, file) for file in image_files]

    # Create a new PDF with ReportLab
    c = canvas.Canvas(path + "/print.pdf", pagesize=letter)
    current_placeholder = 0  # Track the current placeholder index

    for image_path in image_paths:
        if current_placeholder >= len(placeholders):  # Check if a new page is needed
            c.showPage()
            current_placeholder = 0  # Reset placeholder index for new page

        # Get current placeholder
        placeholder = placeholders[current_placeholder]

        # Place image at the placeholder position
        c.drawImage(image_path, placeholder['x'], page.rect.height - placeholder['y'] - placeholder['height'], width=placeholder['width'], height=placeholder['height'])
        current_placeholder += 1

    # Save the final PDF
    c.save()

    # Close the original PDF
    doc.close()

if __name__ == "__main__":
    generate_pdf("labels")