"""Endpoints `GET /admin/{module}/export.pdf` para los listados clave.

Reutilizan los mismos filtros que los listados JSON y devuelven un PDF
generado con `app/pdf/list_export.py`. El frontend solo descarga la URL.

Cada endpoint:
  1. Lee los mismos query params que el endpoint JSON correspondiente.
  2. Arma columns + rows + totals + meta (filtros aplicados).
  3. Llama render_list_pdf y devuelve send_file con content-disposition.
"""
from datetime import date, datetime
from decimal import Decimal

from flask import jsonify, request, send_file
from flask_jwt_extended import current_user
from sqlalchemy import func

from ...permissions import can_see_cost, require_permission
from ...extensions import db
from ...models import (
    AccountReceivable,
    AccountPayable,
    CommissionStatus,
    ItemStatus,
    OperatingExpense,
    PayableStatus,
    Payment,
    PaymentStatus,
    Product,
    ProductItem,
    ReceivableStatus,
    Sale,
    SaleChannel,
    SaleItem,
    SaleStatus,
    StockMovement,
    StockTransfer,
    Store,
    TransferStatus,
    VendorCommission,
    VendorPayout,
)
from ...pdf.list_export import money, render_list_pdf
from . import admin_bp


def _send_pdf(buf, filename: str):
    return send_file(
        buf, mimetype="application/pdf",
        as_attachment=True, download_name=filename,
        max_age=0,
    )


def _today_str():
    return datetime.now().strftime("%Y-%m-%d")


def _label_or_dash(v):
    return v if v not in (None, "") else "—"


# ────────────────────────────────────────────────────────────────────
# 1) VENTAS
# ────────────────────────────────────────────────────────────────────

@admin_bp.get("/sales/export.pdf")
@require_permission("sales.view")
def export_sales_pdf():
    q = Sale.query.order_by(Sale.created_at.desc())
    if channel := request.args.get("channel"):
        q = q.filter(Sale.channel == channel.upper())
    if status := request.args.get("status"):
        q = q.filter(Sale.status == status.upper())
    if pay := request.args.get("payment_status"):
        q = q.filter(Sale.payment_status == pay.upper())
    if search := request.args.get("q"):
        q = q.filter(Sale.number.ilike(f"%{search}%"))
    if frm := request.args.get("from"):
        try: q = q.filter(func.date(Sale.created_at) >= datetime.strptime(frm, "%Y-%m-%d").date())
        except ValueError: pass
    if to := request.args.get("to"):
        try: q = q.filter(func.date(Sale.created_at) <= datetime.strptime(to, "%Y-%m-%d").date())
        except ValueError: pass

    sales = q.limit(1000).all()

    columns = [
        {"label": "Número", "width": 2.5},
        {"label": "Fecha", "width": 2.3},
        {"label": "Canal", "width": 1.8, "align": "center"},
        {"label": "Cliente", "width": 4.5},
        {"label": "Vendedor", "width": 3.8},
        {"label": "Estado", "width": 2.2, "align": "center"},
        {"label": "Pago", "width": 2.0, "align": "center"},
        {"label": "Total", "width": 2.8, "align": "right"},
    ]
    rows = []
    grand_total = Decimal("0")
    for s in sales:
        rows.append([
            s.number,
            s.created_at.strftime("%Y-%m-%d") if s.created_at else "—",
            "WEB" if s.channel == SaleChannel.WEB else "POS",
            (s.customer.name if s.customer else "—"),
            (s.user.full_name if s.user else "—"),
            s.status.value if hasattr(s.status, "value") else str(s.status),
            s.payment_status.value if hasattr(s.payment_status, "value") else str(s.payment_status),
            money(s.total),
        ])
        if s.status == SaleStatus.CONFIRMED:
            grand_total += Decimal(str(s.total or 0))

    meta = {
        "Canal": _label_or_dash(request.args.get("channel")),
        "Estado": _label_or_dash(request.args.get("status")),
        "Pago": _label_or_dash(request.args.get("payment_status")),
        "Búsqueda": _label_or_dash(request.args.get("q")),
        "Desde": _label_or_dash(request.args.get("from")),
        "Hasta": _label_or_dash(request.args.get("to")),
    }
    totals = {"Total confirmadas": money(grand_total), "Cantidad de filas": str(len(sales))}

    buf = render_list_pdf(
        title="Ventas",
        subtitle=f"Generado {_today_str()} · {len(sales)} registros",
        columns=columns,
        rows=rows,
        totals=totals,
        meta=meta,
    )
    return _send_pdf(buf, f"ventas-{_today_str()}.pdf")


# ────────────────────────────────────────────────────────────────────
# 2) COMPRAS
# ────────────────────────────────────────────────────────────────────

@admin_bp.get("/purchases/export.pdf")
@require_permission("purchases.view")
def export_purchases_pdf():
    from ...models import Purchase, PurchaseStatus

    q = Purchase.query.order_by(Purchase.created_at.desc())
    if status := request.args.get("status"):
        q = q.filter(Purchase.status == status.upper())
    if sid := request.args.get("supplier_id"):
        try: q = q.filter(Purchase.supplier_id == int(sid))
        except ValueError: pass
    if search := request.args.get("q"):
        q = q.filter(Purchase.number.ilike(f"%{search}%"))

    purchases = q.limit(1000).all()

    columns = [
        {"label": "Número", "width": 2.5},
        {"label": "Fecha", "width": 2.3},
        {"label": "Proveedor", "width": 5.0},
        {"label": "Sede", "width": 2.5},
        {"label": "Items", "width": 1.8, "align": "center"},
        {"label": "Estado", "width": 2.2, "align": "center"},
        {"label": "Declarado por", "width": 3.8},
        {"label": "Total", "width": 2.8, "align": "right"},
    ]
    rows = []
    grand_total = Decimal("0")
    for p in purchases:
        items_count = len(p.items) if p.items else 0
        units = sum(i.quantity for i in (p.items or []))
        rows.append([
            p.number,
            p.created_at.strftime("%Y-%m-%d") if p.created_at else "—",
            (p.supplier.name if p.supplier else "—"),
            (p.store.code if p.store else "—"),
            f"{items_count} prod / {units} u",
            p.status.value if hasattr(p.status, "value") else str(p.status),
            (p.user.full_name if p.user else "—"),
            money(p.total),
        ])
        grand_total += Decimal(str(p.total or 0))

    meta = {
        "Estado": _label_or_dash(request.args.get("status")),
        "Búsqueda": _label_or_dash(request.args.get("q")),
    }
    totals = {"Total compras": money(grand_total), "Cantidad": str(len(purchases))}

    buf = render_list_pdf(
        title="Compras a proveedores",
        subtitle=f"Generado {_today_str()} · {len(purchases)} registros",
        columns=columns, rows=rows, totals=totals, meta=meta,
    )
    return _send_pdf(buf, f"compras-{_today_str()}.pdf")


# ────────────────────────────────────────────────────────────────────
# 3) GASTOS OPERATIVOS
# ────────────────────────────────────────────────────────────────────

@admin_bp.get("/expenses/export.pdf")
@require_permission("expenses.view")
def export_expenses_pdf():
    q = OperatingExpense.query.order_by(OperatingExpense.paid_at.desc(), OperatingExpense.id.desc())
    if cat := request.args.get("category"):
        q = q.filter(OperatingExpense.category == cat)
    if frm := request.args.get("from"):
        try: q = q.filter(OperatingExpense.paid_at >= datetime.strptime(frm, "%Y-%m-%d").date())
        except ValueError: pass
    if to := request.args.get("to"):
        try: q = q.filter(OperatingExpense.paid_at <= datetime.strptime(to, "%Y-%m-%d").date())
        except ValueError: pass

    expenses = q.limit(2000).all()

    columns = [
        {"label": "Fecha", "width": 2.3},
        {"label": "Categoría", "width": 2.8},
        {"label": "Descripción", "width": 7.0},
        {"label": "Método", "width": 3.5},
        {"label": "Referencia", "width": 3.0},
        {"label": "Cargado por", "width": 3.5},
        {"label": "Monto", "width": 2.5, "align": "right"},
    ]
    rows = []
    grand_total = Decimal("0")
    by_cat = {}
    for e in expenses:
        rows.append([
            e.paid_at.strftime("%Y-%m-%d") if e.paid_at else "—",
            e.category.title(),
            e.description,
            (e.payment_method.name if e.payment_method else "—"),
            e.reference or "—",
            (e.user.full_name if e.user else "—"),
            money(e.amount),
        ])
        amt = Decimal(str(e.amount or 0))
        grand_total += amt
        by_cat[e.category] = by_cat.get(e.category, Decimal("0")) + amt

    meta = {
        "Categoría": _label_or_dash(request.args.get("category")),
        "Desde": _label_or_dash(request.args.get("from")),
        "Hasta": _label_or_dash(request.args.get("to")),
    }
    totals = {"Total gastado": money(grand_total), "Cantidad": str(len(expenses))}
    # Si hay varias categorías, listarlas aparte como totales por categoría.
    if len(by_cat) > 1:
        for cat, amt in sorted(by_cat.items(), key=lambda x: -x[1]):
            totals[f"  {cat.title()}"] = money(amt)

    buf = render_list_pdf(
        title="Gastos operativos",
        subtitle=f"Generado {_today_str()} · {len(expenses)} registros",
        columns=columns, rows=rows, totals=totals, meta=meta,
    )
    return _send_pdf(buf, f"gastos-{_today_str()}.pdf")


# ────────────────────────────────────────────────────────────────────
# 4) FINANZAS — Reporte P&L del período
# ────────────────────────────────────────────────────────────────────

@admin_bp.get("/finance/export.pdf")
@require_permission("finance.view")
def export_finance_pdf():
    today = date.today()
    month_start = today.replace(day=1)

    def _parse(s, default):
        if not s: return default
        try: return datetime.strptime(s, "%Y-%m-%d").date()
        except ValueError: return default

    f = _parse(request.args.get("from"), month_start)
    t = _parse(request.args.get("to"), today)

    # Base de cuentas = subtotal (sin recargos/descuentos, que son fees).
    sales_agg = db.session.query(
        func.coalesce(func.sum(Sale.subtotal), 0),
        func.coalesce(func.sum(func.greatest(Sale.total - Sale.subtotal, 0)), 0),
        func.coalesce(func.sum(func.greatest(Sale.subtotal - Sale.total, 0)), 0),
    ).filter(
        Sale.status == SaleStatus.CONFIRMED,
        func.date(Sale.created_at).between(f, t),
    ).one()
    sales_total = Decimal(str(sales_agg[0] or 0))
    sales_surcharge = Decimal(str(sales_agg[1] or 0))
    sales_discount = Decimal(str(sales_agg[2] or 0))
    sales_count = db.session.query(func.count(Sale.id)).filter(
        Sale.status == SaleStatus.CONFIRMED,
        func.date(Sale.created_at).between(f, t),
    ).scalar() or 0

    cogs = (
        db.session.query(func.coalesce(func.sum(ProductItem.cost), 0))
        .join(SaleItem, SaleItem.product_item_id == ProductItem.id)
        .join(Sale, Sale.id == SaleItem.sale_id)
        .filter(
            Sale.status == SaleStatus.CONFIRMED,
            func.date(Sale.created_at).between(f, t),
        )
        .scalar()
    ) or Decimal("0")

    op_expenses_q = db.session.query(
        OperatingExpense.category,
        func.coalesce(func.sum(OperatingExpense.amount), 0),
    ).filter(OperatingExpense.paid_at.between(f, t)).group_by(OperatingExpense.category).all()
    op_expenses_total = sum((Decimal(str(r[1])) for r in op_expenses_q), Decimal("0"))

    commissions = db.session.query(
        func.coalesce(func.sum(VendorCommission.amount), 0),
    ).filter(
        VendorCommission.status != CommissionStatus.REVERSED,
        func.date(VendorCommission.created_at).between(f, t),
    ).scalar() or Decimal("0")

    sales_total = Decimal(str(sales_total))
    cogs = Decimal(str(cogs))
    commissions = Decimal(str(commissions))
    gross = sales_total - cogs
    net = gross - op_expenses_total - commissions
    margin_pct = (net / sales_total * 100) if sales_total > 0 else Decimal("0")

    columns = [
        {"label": "Concepto", "width": 9.0},
        {"label": "Monto USD", "width": 4.0, "align": "right"},
    ]
    rows = [
        ["Ventas confirmadas (subtotal)", money(sales_total)],
        [f"  ({sales_count} ventas en el período)", ""],
        [f"  (+) Recargos cobrados (fee, no es ganancia)", money(sales_surcharge)],
        [f"  (−) Descuentos otorgados", money(sales_discount)],
        ["", ""],
        ["(−) Costo de mercadería vendida (COGS)", money(cogs)],
        ["", ""],
        ["UTILIDAD BRUTA", money(gross)],
        ["", ""],
        ["(−) Gastos operativos", money(op_expenses_total)],
    ]
    for cat, amt in sorted(op_expenses_q, key=lambda r: -float(r[1])):
        rows.append([f"     · {cat.title()}", money(amt)])
    rows.extend([
        ["", ""],
        ["(−) Comisiones devengadas a vendedores", money(commissions)],
        ["", ""],
        ["UTILIDAD NETA", money(net)],
        [f"Margen sobre ventas", f"{margin_pct:.2f}%"],
    ])

    meta = {
        "Período desde": f.isoformat(),
        "Período hasta": t.isoformat(),
        "Generado": _today_str(),
    }
    totals = {"UTILIDAD NETA": money(net)}

    buf = render_list_pdf(
        title="Estado de resultados (P&L)",
        subtitle=f"Período {f.isoformat()} → {t.isoformat()}",
        columns=columns, rows=rows, totals=totals, meta=meta,
        landscape_mode=False,  # P&L luce mejor en portrait
    )
    return _send_pdf(buf, f"pyl-{f.isoformat()}_a_{t.isoformat()}.pdf")


# ────────────────────────────────────────────────────────────────────
# 7) PRODUCTOS (catálogo)
# ────────────────────────────────────────────────────────────────────

@admin_bp.get("/products/export.pdf")
@require_permission("products.view")
def export_products_pdf():
    from ...models import Brand, Category, ProductKind

    # Stock disponible por producto (subquery rápida).
    stock_sq = (
        db.session.query(
            ProductItem.product_id.label("pid"),
            func.sum(
                db.case((ProductItem.status == ItemStatus.AVAILABLE, 1), else_=0)
            ).label("avail"),
        )
        .group_by(ProductItem.product_id)
        .subquery()
    )

    q = (
        db.session.query(Product, stock_sq.c.avail)
        .outerjoin(stock_sq, stock_sq.c.pid == Product.id)
    )
    if search := request.args.get("q"):
        like = f"%{search}%"
        q = q.filter(
            (Product.name.ilike(like)) | (Product.sku.ilike(like)) | (Product.model.ilike(like))
        )
    if brand_id := request.args.get("brand_id"):
        try: q = q.filter(Product.brand_id == int(brand_id))
        except ValueError: pass
    if cat_id := request.args.get("category_id"):
        try: q = q.filter(Product.category_id == int(cat_id))
        except ValueError: pass
    if (active := request.args.get("is_active")) is not None and active != "":
        q = q.filter(Product.is_active == (active.lower() == "true"))
    if kind := request.args.get("kind"):
        q = q.filter(Product.kind == kind)

    q = q.order_by(Product.name).limit(3000)
    results = q.all()

    columns = [
        {"label": "SKU", "width": 2.8},
        {"label": "Producto", "width": 6.5},
        {"label": "Marca", "width": 2.5},
        {"label": "Categoría", "width": 2.5},
        {"label": "Tipo", "width": 1.5, "align": "center"},
        {"label": "Precio", "width": 2.3, "align": "right"},
        {"label": "Comisión %", "width": 1.8, "align": "right"},
        {"label": "Disponibles", "width": 2.0, "align": "center"},
        {"label": "Activo", "width": 1.5, "align": "center"},
    ]
    rows = []
    total_avail = 0
    total_value = Decimal("0")
    by_kind = {"SIMPLE": 0, "COMBO": 0}
    for p, avail in results:
        a = int(avail or 0)
        total_avail += a
        total_value += Decimal(str(p.price or 0)) * a
        kind_val = p.kind.value if hasattr(p.kind, "value") else str(p.kind)
        by_kind[kind_val.upper()] = by_kind.get(kind_val.upper(), 0) + 1
        rows.append([
            p.sku,
            p.name,
            (p.brand.name if p.brand else "—"),
            (p.category.name if p.category else "—"),
            "Combo" if p.kind == ProductKind.COMBO else "Simple",
            money(p.price),
            f"{p.commission_percent or 0}%",
            str(a),
            "Sí" if p.is_active else "No",
        ])

    meta = {
        "Búsqueda": _label_or_dash(request.args.get("q")),
        "Marca": _label_or_dash(request.args.get("brand_id")),
        "Categoría": _label_or_dash(request.args.get("category_id")),
        "Tipo": _label_or_dash(request.args.get("kind")),
        "Activos": _label_or_dash(request.args.get("is_active")),
    }
    totals = {
        "Productos": str(len(results)),
        "  Simples": str(by_kind.get("SIMPLE", 0)),
        "  Combos": str(by_kind.get("COMBO", 0)),
        "Unidades disponibles": str(total_avail),
        "Valor stock disponible": money(total_value),
    }

    buf = render_list_pdf(
        title="Catálogo de productos",
        subtitle=f"Generado {_today_str()} · {len(results)} productos",
        columns=columns, rows=rows, totals=totals, meta=meta,
    )
    return _send_pdf(buf, f"productos-{_today_str()}.pdf")


# ────────────────────────────────────────────────────────────────────
# 8) IPHONES (módulo especializado)
# ────────────────────────────────────────────────────────────────────

@admin_bp.get("/iphones/export.pdf")
@require_permission("iphones.view")
def export_iphones_pdf():
    q = (
        ProductItem.query.join(Product, ProductItem.product_id == Product.id)
        .outerjoin(Store, Store.id == ProductItem.store_id)
        .filter(Product.is_iphone.is_(True))
    )
    if search := request.args.get("q"):
        like = f"%{search}%"
        q = q.filter(
            (ProductItem.imei.ilike(like))
            | (ProductItem.serial.ilike(like))
            | (Product.name.ilike(like))
        )
    if pid := request.args.get("product_id"):
        try: q = q.filter(ProductItem.product_id == int(pid))
        except ValueError: pass
    if color := request.args.get("color"):
        q = q.filter(ProductItem.color.ilike(color))
    if status := request.args.get("status"):
        q = q.filter(ProductItem.status == status.lower())
    if store_id := request.args.get("store_id"):
        try: q = q.filter(ProductItem.store_id == int(store_id))
        except ValueError: pass
    bmin = request.args.get("battery_min")
    bmax = request.args.get("battery_max")
    if bmin not in (None, ""):
        try: q = q.filter(ProductItem.battery_pct >= int(bmin))
        except ValueError: pass
    if bmax not in (None, ""):
        try: q = q.filter(ProductItem.battery_pct <= int(bmax))
        except ValueError: pass

    items = q.order_by(ProductItem.created_at.desc()).limit(2000).all()

    # El costo y el margen son info sensible: SOLO admin (can_see_cost).
    # Vendedor e inventario ven precios pero no costos.
    show_cost = can_see_cost(current_user)

    columns = [
        {"label": "Modelo", "width": 5.5},
        {"label": "Color", "width": 2.2},
        {"label": "Serial", "width": 3.0},
        {"label": "IMEI", "width": 3.5},
        {"label": "Batería", "width": 1.8, "align": "center"},
        {"label": "Sede", "width": 2.5},
        {"label": "Estado", "width": 2.0, "align": "center"},
    ]
    if show_cost:
        columns.append({"label": "Costo", "width": 2.0, "align": "right"})
    columns.append({"label": "Precio", "width": 2.2, "align": "right"})

    rows = []
    by_status = {}
    total_value = Decimal("0")
    total_cost = Decimal("0")
    for it in items:
        st = it.status.value if hasattr(it.status, "value") else str(it.status)
        by_status[st] = by_status.get(st, 0) + 1
        price_val = it.effective_price if it.effective_price is not None else (it.price if hasattr(it, "price") else None)
        # La valuación (costo / valor / margen) cuenta SOLO unidades disponibles.
        if st == "available":
            total_value += Decimal(str(price_val or 0))
            total_cost += Decimal(str(it.cost or 0))
        row = [
            it.product.name if it.product else "—",
            it.color or "—",
            it.serial or "—",
            it.imei or "—",
            f"{it.battery_pct}%" if it.battery_pct is not None else "—",
            (it.store.code if it.store else "—"),
            st,
        ]
        if show_cost:
            row.append(money(it.cost))
        row.append(money(price_val))
        rows.append(row)

    meta = {
        "Búsqueda": _label_or_dash(request.args.get("q")),
        "Modelo": _label_or_dash(request.args.get("product_id")),
        "Color": _label_or_dash(request.args.get("color")),
        "Estado": _label_or_dash(request.args.get("status")),
        "Sede": _label_or_dash(request.args.get("store_id")),
        "Batería desde": _label_or_dash(request.args.get("battery_min")),
        "Batería hasta": _label_or_dash(request.args.get("battery_max")),
    }
    totals = {"Unidades": str(len(items))}
    if show_cost:
        totals["Costo total (disponible)"] = money(total_cost)
        totals["Valor en venta (disponible)"] = money(total_value)
        totals["Margen estimado (disponible)"] = money(total_value - total_cost)
    else:
        totals["Valor en venta (disponible)"] = money(total_value)
    for st_name, count in sorted(by_status.items(), key=lambda x: -x[1]):
        totals[f"  {st_name}"] = str(count)

    buf = render_list_pdf(
        title="iPhones — módulo especializado",
        subtitle=f"Generado {_today_str()} · {len(items)} unidades",
        columns=columns, rows=rows, totals=totals, meta=meta,
    )
    return _send_pdf(buf, f"iphones-{_today_str()}.pdf")


# ────────────────────────────────────────────────────────────────────
# 5) STOCK GLOBAL
# ────────────────────────────────────────────────────────────────────

@admin_bp.get("/stock/export.pdf")
@require_permission("stock.view")
def export_stock_pdf():
    # Stock por producto: cuenta unidades disponibles agrupadas por producto + sede.
    rows_q = (
        db.session.query(
            Product.id, Product.sku, Product.name,
            Product.price,
            Store.id.label("store_id"), Store.code.label("store_code"), Store.name.label("store_name"),
            func.sum(
                db.case((ProductItem.status == ItemStatus.AVAILABLE, 1), else_=0)
            ).label("avail"),
            func.count(ProductItem.id).label("total_units"),
        )
        .join(ProductItem, ProductItem.product_id == Product.id)
        .outerjoin(Store, Store.id == ProductItem.store_id)
        .filter(Product.is_active.is_(True))
        # Stock = solo unidades DISPONIBLES.
        .filter(ProductItem.status == ItemStatus.AVAILABLE)
    )
    if search := request.args.get("q"):
        like = f"%{search}%"
        rows_q = rows_q.filter((Product.name.ilike(like)) | (Product.sku.ilike(like)))
    if sid := request.args.get("store_id"):
        try: rows_q = rows_q.filter(Store.id == int(sid))
        except ValueError: pass

    results = (
        rows_q.group_by(Product.id, Store.id)
        .having(func.count(ProductItem.id) > 0)
        .order_by(Product.name, Store.code)
        .limit(3000).all()
    )

    columns = [
        {"label": "SKU", "width": 2.8},
        {"label": "Producto", "width": 8.5},
        {"label": "Sede", "width": 3.5},
        {"label": "Precio", "width": 2.5, "align": "right"},
        {"label": "Disponibles", "width": 2.5, "align": "center"},
    ]
    rows = []
    total_avail = 0
    for r in results:
        rows.append([
            r.sku, r.name,
            f"{r.store_code} · {r.store_name}" if r.store_code else "—",
            money(r.price),
            str(int(r.avail or 0)),
        ])
        total_avail += int(r.avail or 0)

    meta = {
        "Búsqueda": _label_or_dash(request.args.get("q")),
        "Sede": _label_or_dash(request.args.get("store_id")),
    }
    totals = {
        "Unidades disponibles": str(total_avail),
        "Cantidad de filas": str(len(rows)),
    }

    buf = render_list_pdf(
        title="Stock disponible por producto y sede",
        subtitle=f"Generado {_today_str()}",
        columns=columns, rows=rows, totals=totals, meta=meta,
    )
    return _send_pdf(buf, f"stock-{_today_str()}.pdf")


# ────────────────────────────────────────────────────────────────────
# 6) MOVIMIENTOS DE INVENTARIO (audit)
# ────────────────────────────────────────────────────────────────────

@admin_bp.get("/audit/movements/export.pdf")
@require_permission("audit.view")
def export_audit_movements_pdf():
    q = StockMovement.query.order_by(StockMovement.created_at.desc())
    if mt := request.args.get("type"):
        q = q.filter(StockMovement.type == mt.upper())
    if frm := request.args.get("from"):
        try: q = q.filter(func.date(StockMovement.created_at) >= datetime.strptime(frm, "%Y-%m-%d").date())
        except ValueError: pass
    if to := request.args.get("to"):
        try: q = q.filter(func.date(StockMovement.created_at) <= datetime.strptime(to, "%Y-%m-%d").date())
        except ValueError: pass

    movs = q.limit(3000).all()

    columns = [
        {"label": "Fecha", "width": 3.0},
        {"label": "Tipo", "width": 2.5, "align": "center"},
        {"label": "Producto", "width": 5.0},
        {"label": "Serial", "width": 3.0},
        {"label": "Usuario", "width": 3.5},
        {"label": "Referencia", "width": 3.0},
        {"label": "Notas", "width": 5.5},
    ]
    rows = []
    for m in movs:
        item = m.item
        prod_name = (item.product.name if item and item.product else "—")
        rows.append([
            m.created_at.strftime("%Y-%m-%d %H:%M") if m.created_at else "—",
            m.type.value if hasattr(m.type, "value") else str(m.type),
            prod_name,
            (item.serial if item else "—"),
            (m.user.full_name if m.user else "—"),
            f"{m.reference_type}#{m.reference_id}" if m.reference_type and m.reference_id else "—",
            (m.notes[:80] + "…" if m.notes and len(m.notes) > 80 else (m.notes or "—")),
        ])

    meta = {
        "Tipo de movimiento": _label_or_dash(request.args.get("type")),
        "Desde": _label_or_dash(request.args.get("from")),
        "Hasta": _label_or_dash(request.args.get("to")),
    }
    totals = {"Movimientos": str(len(movs))}

    buf = render_list_pdf(
        title="Movimientos de inventario",
        subtitle=f"Generado {_today_str()} · {len(movs)} registros",
        columns=columns, rows=rows, totals=totals, meta=meta,
    )
    return _send_pdf(buf, f"movimientos-{_today_str()}.pdf")


# ────────────────────────────────────────────────────────────────────
# 9) TRANSFERENCIAS ENTRE SEDES
# ────────────────────────────────────────────────────────────────────

@admin_bp.get("/transfers/export.pdf")
@require_permission("transfers.view")
def export_transfers_pdf():
    q = StockTransfer.query.order_by(StockTransfer.created_at.desc())
    if status := request.args.get("status"):
        q = q.filter(StockTransfer.status == status.upper())
    if sid := request.args.get("from_store_id"):
        try: q = q.filter(StockTransfer.from_store_id == int(sid))
        except ValueError: pass
    if sid := request.args.get("to_store_id"):
        try: q = q.filter(StockTransfer.to_store_id == int(sid))
        except ValueError: pass

    transfers = q.limit(2000).all()

    columns = [
        {"label": "Número", "width": 2.5},
        {"label": "Creada", "width": 2.3},
        {"label": "Origen → Destino", "width": 3.5, "align": "center"},
        {"label": "Items", "width": 1.5, "align": "center"},
        {"label": "Estado", "width": 2.5, "align": "center"},
        {"label": "Creó", "width": 3.5},
        {"label": "Designado", "width": 3.5},
        {"label": "Recibió", "width": 3.5},
        {"label": "Recibida", "width": 2.3},
    ]
    rows = []
    by_status = {}
    for t in transfers:
        st = t.status.value if hasattr(t.status, "value") else str(t.status)
        by_status[st] = by_status.get(st, 0) + 1
        rows.append([
            t.number,
            t.created_at.strftime("%Y-%m-%d") if t.created_at else "—",
            f"{t.from_store.code if t.from_store else '?'} → {t.to_store.code if t.to_store else '?'}",
            str(len(t.items) if t.items else 0),
            st,
            (t.user.full_name if t.user else "—"),
            (t.assigned_receiver.full_name if t.assigned_receiver else "—"),
            (t.received_by.full_name if t.received_by else "—"),
            t.received_at.strftime("%Y-%m-%d") if t.received_at else "—",
        ])

    meta = {
        "Estado": _label_or_dash(request.args.get("status")),
        "Sede origen": _label_or_dash(request.args.get("from_store_id")),
        "Sede destino": _label_or_dash(request.args.get("to_store_id")),
    }
    totals = {"Transferencias": str(len(transfers))}
    for st_name, count in sorted(by_status.items(), key=lambda x: -x[1]):
        totals[f"  {st_name}"] = str(count)

    buf = render_list_pdf(
        title="Transferencias entre sedes",
        subtitle=f"Generado {_today_str()} · {len(transfers)} transferencias",
        columns=columns, rows=rows, totals=totals, meta=meta,
    )
    return _send_pdf(buf, f"transferencias-{_today_str()}.pdf")
