from PIL import Image
from flask import current_app

from app.labels.template_renderer import get_template, render_template


def generate(
    sku: str,
    product_name: str,
    quantity: int,
    order_number: str,
    warehouse_location: str = None,
    item_price: float = None,
    currency: str = 'EUR',
    letter: str = None,
    barcode_id: str = None,
) -> Image.Image:
    """Generate a 55×32mm (440×256 dot) order item label as a PIL Image.

    barcode_id overrides order_number in the barcode when set (used for long
    order numbers that don't fit in a Code-128 barcode at label size).
    """
    price_str = f'{item_price:.2f} {currency}' if item_price is not None else ''
    bc_prefix = barcode_id or order_number
    fields = {
        'sku':          sku,
        'product_url':  f'solde.red/{sku}',
        'location':     warehouse_location or '',
        'qty_name':     f'{quantity}\u00d7 {(product_name or sku)[:28]}',
        'item_price':   price_str,
        'barcode_data': f'{bc_prefix}{sku}',
        'letter':       letter or '',
    }
    db_path = current_app.config['DATABASE_PATH']
    template = get_template('order_item', db_path)
    return render_template(template, fields)
