from PIL import Image, ImageDraw, ImageFont
import qrcode
from io import BytesIO
import zipfile

def generate_qr_images(image_path, qr_data, start_num, end_num, increment,
                       show_text=False, qr_color='#000000', bg_color='#FFFFFF', text_color='#000000',
                       leading_zeros=0, font_size=40):  # Accept font_size from the frontend
    images = []

    
    try:
        # Load custom font with the font_size provided by frontend
        font = ImageFont.truetype("Arial-bold.ttf", font_size)
    except Exception as e:
        # Fallback to default font if Arial is not available
        print(f"Error loading custom font: {e}")
        font = ImageFont.load_default()

    pad_length = leading_zeros if leading_zeros > 0 else len(str(end_num))

    for number in range(start_num, end_num + 1, increment):
        with Image.open(image_path) as background:
            background = background.convert('RGB')

            for qr in qr_data:
                padded_number = str(number).zfill(pad_length)

                qr_code = qrcode.QRCode(
                    version=1,
                    error_correction=qrcode.constants.ERROR_CORRECT_L,
                    box_size=10,
                    border=1.5
                )
                qr_code.add_data(padded_number)
                qr_code.make(fit=True)

                qr_img = qr_code.make_image(
                    fill_color=qr_color,
                    back_color=bg_color
                ).convert('RGB')

                qr_img = qr_img.resize((qr['width'], qr['height']))
                background.paste(qr_img, (qr['x'], qr['y']))

                if show_text:
                    draw = ImageDraw.Draw(background)
                    text = padded_number
                    text_width = draw.textlength(text, font=font)
                    text_x = qr['x'] + (qr['width'] - text_width) / 2
                    text_y = qr['y'] + qr['height'] + 7
                    draw.text((text_x, text_y), text, font=font, fill=text_color)

            img_bytes = BytesIO()
            background.save(img_bytes, format='PNG')
            images.append((f'qr_image_{padded_number}.png', img_bytes.getvalue()))

    zip_buffer = BytesIO()
    with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for name, data in images:
            zipf.writestr(name, data)
    zip_buffer.seek(0)
    return zip_buffer
