from brother_ql.raster import BrotherQLRaster
from brother_ql.backends.helpers import send
from brother_ql.conversion import convert
from PIL import Image, ImageDraw, ImageFont
import sys
import os

def create_image(text):
    img_width = 696  # ~100mm at 200dpi
    img_height = 200  # ~24mm label height
    img = Image.new('RGB', (img_width, img_height), color='white')
    draw = ImageDraw.Draw(img)

    try:
        font = ImageFont.truetype("arial.ttf", 40)
    except:
        font = ImageFont.load_default()

    # Use textbbox instead of deprecated textsize
    bbox = draw.textbbox((0, 0), text, font=font)
    w = bbox[2] - bbox[0]
    h = bbox[3] - bbox[1]
    draw.text(((img_width - w) / 2, (img_height - h) / 2), text, font=font, fill='black')

    path = os.path.join(os.getcwd(), "label_output.png")
    img.save(path)
    return path

def print_label(text):
    qlr = BrotherQLRaster('QL-700')  # Use compatible model
    qlr.exception_on_warning = True

    label_path = create_image(text)

    instructions = convert(
        qlr=qlr,
        images=[label_path],
        label='62',
        rotate='0',
        threshold=70.0,
        dither=False,
        compress=False,
        red=False,
        dpi_600=False,
        hq=False,
        cut=True
    )

    send(
        instructions=instructions,
        printer_identifier='usb://0x4f9:0x2060',
        backend_identifier='pyusb',
        blocking=True
    )

if __name__ == '__main__':
    if len(sys.argv) > 1:
        print_label(sys.argv[1])
    else:
        print("❌ Error: No label text provided.")
