"""Generador de etiqueta imprimible para una unidad (ProductItem).

Genera un PDF de tamaño 80×50mm con:
  - Nombre del producto (truncado si es muy largo)
  - Código de barras CODE128 grande (centrado)
  - Texto del barcode debajo (legible)
  - Serial (chico, esquina sup. izq.)
  - Precio destacado (esquina inf. derecha)

Pensado para impresoras de etiquetas térmicas o impresión casera A4 (1 etiqueta
por hoja, recortable). NO usa el `BrandedDocTemplate` corporativo porque la
etiqueta es chica y necesita máximo espacio para el barcode.
"""
from __future__ import annotations

import io
from decimal import Decimal

import barcode
from barcode.writer import ImageWriter
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import mm
from reportlab.lib.utils import ImageReader
from reportlab.pdfgen.canvas import Canvas


LABEL_WIDTH = 80 * mm
LABEL_HEIGHT = 50 * mm
PAD = 3 * mm

# === Layout de hoja A4 para impresión en lote ===
# A4 = 210×297mm. 2 columnas × 5 filas = 10 etiquetas/hoja con márgenes generosos.
A4_W, A4_H = A4
SHEET_COLS = 2
SHEET_ROWS = 5
SHEET_MARGIN_X = (A4_W - SHEET_COLS * LABEL_WIDTH) / 2
SHEET_MARGIN_Y = (A4_H - SHEET_ROWS * LABEL_HEIGHT) / 2
LABELS_PER_SHEET = SHEET_COLS * SHEET_ROWS


def _truncate(s: str, max_chars: int) -> str:
    if s is None:
        return ""
    s = str(s)
    return s if len(s) <= max_chars else s[: max_chars - 1] + "…"


def _format_price(value) -> str | None:
    if value is None:
        return None
    try:
        d = Decimal(str(value)).quantize(Decimal("0.01"))
    except Exception:
        return None
    if d <= 0:
        return None
    return f"${d:,.2f}"


def _draw_label_at(c: Canvas, item, origin_x: float, origin_y: float) -> None:
    """Dibuja una etiqueta en la posición `(origin_x, origin_y)` del canvas.

    El bounding box de la etiqueta es `LABEL_WIDTH × LABEL_HEIGHT`. La función
    no llama a `showPage()` — esa decisión es de quien la usa (1 etiqueta por
    página en modo single, grilla en modo lote).
    """
    # ── Borde sutil (guía de recorte si se imprime en hoja grande) ──
    c.setStrokeColor(colors.HexColor("#bcbcc4"))
    c.setLineWidth(0.3)
    c.rect(origin_x + 0.5, origin_y + 0.5,
           LABEL_WIDTH - 1, LABEL_HEIGHT - 1, fill=0, stroke=1)

    # ── Producto (top, truncado) ──
    product_name = item.product.name if item.product else "Producto"
    c.setFillColor(colors.black)
    c.setFont("Helvetica-Bold", 9)
    c.drawString(origin_x + PAD, origin_y + LABEL_HEIGHT - PAD - 7,
                 _truncate(product_name, 38))

    # SKU debajo del nombre
    if item.product and item.product.sku:
        c.setFont("Helvetica", 6.5)
        c.setFillColor(colors.HexColor("#6b6b76"))
        c.drawString(origin_x + PAD, origin_y + LABEL_HEIGHT - PAD - 13.5,
                     f"SKU {item.product.sku}")

    # ── Código de barras CODE128 centrado en la franja media ──
    bc = barcode.get("code128", item.barcode, writer=ImageWriter())
    bc_buf = io.BytesIO()
    bc.write(
        bc_buf,
        options={
            "module_width": 0.32,
            "module_height": 11.0,
            "font_size": 7,
            "text_distance": 1.5,
            "quiet_zone": 1.5,
            "write_text": True,
        },
    )
    bc_buf.seek(0)
    bc_img = ImageReader(bc_buf)
    iw, ih = bc_img.getSize()

    max_w = LABEL_WIDTH - PAD * 2
    target_h = 18 * mm
    target_w = min(max_w, iw * target_h / ih)
    bx = origin_x + (LABEL_WIDTH - target_w) / 2
    by = origin_y + (LABEL_HEIGHT - target_h) / 2 - 1 * mm
    c.drawImage(bc_img, bx, by, width=target_w, height=target_h, mask="auto")

    # ── Pie: serial (izq) + precio (der) ──
    c.setFont("Helvetica", 6.5)
    c.setFillColor(colors.HexColor("#4a4a52"))
    if item.serial:
        c.drawString(origin_x + PAD, origin_y + PAD,
                     f"S/N: {_truncate(item.serial, 28)}")

    price_text = _format_price(getattr(item, "effective_price", None))
    if price_text:
        c.setFont("Helvetica-Bold", 13)
        c.setFillColor(colors.black)
        c.drawRightString(origin_x + LABEL_WIDTH - PAD,
                          origin_y + PAD - 0.5, price_text)


def build_item_label_pdf(item) -> io.BytesIO:
    """PDF de UNA etiqueta tamaño 80×50mm. Para impresoras térmicas o
    impresión casera (1 etiqueta por página)."""
    buf = io.BytesIO()
    c = Canvas(buf, pagesize=(LABEL_WIDTH, LABEL_HEIGHT))
    _draw_label_at(c, item, 0, 0)
    c.showPage()
    c.save()
    buf.seek(0)
    return buf


def build_items_labels_sheet_pdf(items) -> io.BytesIO:
    """PDF con N etiquetas en hojas A4, grilla 2×5 = 10 por hoja.

    `items` es un iterable de `ProductItem`. El orden de impresión es
    fila por fila de arriba a abajo (lectura natural). Páginas adicionales
    se agregan automáticamente si hay > 10 items.
    """
    buf = io.BytesIO()
    c = Canvas(buf, pagesize=A4)

    for idx, item in enumerate(items):
        if item is None:
            continue
        slot = idx % LABELS_PER_SHEET
        if slot == 0 and idx > 0:
            c.showPage()
        col = slot % SHEET_COLS
        row = slot // SHEET_COLS
        x = SHEET_MARGIN_X + col * LABEL_WIDTH
        # Y en reportlab crece hacia arriba: la fila 0 está arriba.
        y = A4_H - SHEET_MARGIN_Y - (row + 1) * LABEL_HEIGHT
        _draw_label_at(c, item, x, y)

    c.showPage()
    c.save()
    buf.seek(0)
    return buf
