"""
REVISA_CANT_vs_PESONETO_KGS / REVISA_CANT_vs_PESONETO_LBS
Validates that the net weight of each export line matches its quantity
when the line's unit of measure is weight-based (KGS or LBS).

Rule (identical for both variants, only the unit differs):
  - KGS: if UnitOfMeasure = 'KGS' → net_weight_kgs must equal quantity
  - LBS: if UnitOfMeasure = 'LBS' → net_weight_lbs must equal quantity

Legacy equivalents
------------------
KGS:
  SELECT COUNT(*) FROM QEqeMaq
  WHERE Consecutivo = <id> AND UnidadMedida = 'KGS' AND PesoNetoKGS <> CantExpo

LBS:
  SELECT COUNT(*) FROM QEqeMaq
  WHERE Consecutivo = <id> AND UnidadMedida = 'LBS' AND PesoNetoLBS <> CantExpo
"""

from decimal import Decimal
from typing import List

from sqlalchemy.orm import Session

from api.v1.modules.a76.invoices.models import InvoiceHeader
from api.v1.modules.a76.items.models import LineItem
from core.exceptions import ErrorCollector

_UNIT_KGS = "KGS"
_UNIT_LBS = "LBS"


def review_qty_vs_weight(
    lines: List[LineItem],
    unit_code: str,    
    errors: ErrorCollector,
) -> None:
    """
    Generic validator used by both KGS and LBS variants.

    For every line whose unit of measure code matches ``unit_code``,
    checks that the exported quantity equals the net weight.  Adds a PESO_NETO error for each mismatch.

    Parameters
    ----------
    lines       : all LineItem rows for the invoice
    unit_code   : 'KGS' or 'LBS' — only lines with this UOM are evaluated    
    errors      : collector for validation errors
    """
    for line in lines:
        uom = line.unit_of_measure_info
        if uom is None:
            continue

        line_uom_code = (uom.code or "").strip().upper()
        if line_uom_code != unit_code:
            continue

        if line.quantity is None:
            continue

        qty = line.quantity.quantity or Decimal(0)
        net_weight = line.quantity.net_weight or Decimal(0)

        if net_weight != qty:
            errors.add_error(
                field=f"line[{line.line_number}].quantity",
                message=f"La cantidad es de {qty} {unit_code} y el Peso Neto es de {net_weight} {unit_code}.",
                solution=["Igualar el Peso Neto con la cantidad a Exportar."],
                code="PESO_NETO",
            )