"""
VERIFICAQCONSOLIDADO
Second-pass check after COMPARA_SALDOS_POR_FACTURA: iterates every discharge
entry and reports an error for any line that still has unmet quantity
(QADesc:Cantidad - QADesc:CantUsada <> 0).

The Clarion routine distinguishes TEM vs DEF in the error message; this
translation preserves that distinction.

Note: compare_balances already raises INSUFFICIENT_BALANCE errors per entry.
This routine acts as a final consolidation gate — if compare_balances is
called with raise_if_errors() afterwards, this function may be redundant in
practice.  It is kept as a faithful port and can serve as the sole
insufficient-balance check if compare_balances is ever made non-raising.
"""

from typing import List

from sqlalchemy.orm import Session

from api.v1.modules.a76.invoices.models import InvoiceHeader
from core.exceptions import ErrorCollector
from .discharge_types import DownloadEntry


def verify_consolidated(
    db: Session,
    export_invoice: InvoiceHeader,
    to_discharge: List[DownloadEntry],
    errors: ErrorCollector,
) -> None:
    """
    VERIFICAQCONSOLIDADO
    Reports an error for every discharge entry whose quantity was not fully
    satisfied by ``compare_balances``.

    Parameters
    ----------
    db              : active SQLAlchemy session
    export_invoice  : the export invoice being processed
    to_discharge    : list of DownloadEntry objects after compare_balances ran
    errors          : shared error collector
    """
    # Sort mirrors Clarion: Sort(QueADescargar, -Procedencia, FacturaImpo, LineaImpo)
    sorted_entries = sorted(
        to_discharge,
        key=lambda e: (e.origin_procedure, e.import_invoice, e.import_line),
        reverse=True,
    )

    for entry in sorted_entries:
        remaining = entry.quantity - entry.quantity_used
        if remaining == 0:
            continue

        uom = entry.unit_of_measure or ""
        procedure = (entry.origin_procedure or "").strip().upper()

        if procedure == "TEM":
            message = (
                f"Insuficiencia TEM: La Linea: {entry.export_line} se quiere "
                f"descargar: {entry.quantity} {uom} y hay: {entry.quantity_used} {uom}."
            )
        else:  # DEF or any other
            message = (
                f"Insuficiencia DEF.: La Linea: {entry.export_line} se quiere "
                f"descargar: {entry.quantity} {uom} y hay: {entry.quantity_used} {uom}."
            )

        errors.add_error(
            field=f"line[{entry.export_line}].quantity",
            message=message,
            solution=["Asignar Facturas con Saldos Disponibles."],
            code="INSUFFICIENT_BALANCE_CONSOLIDATED",
            value={
                "export_line": entry.export_line,
                "required": str(entry.quantity),
                "available": str(entry.quantity_used),
                "shortage": str(remaining),
                "origin_procedure": procedure,
            },
        )
