"""
REVISA_PROCEDENCIA_PAR
Validates that every line item of the export invoice has an import origin
procedure (TipoMovImpo) that matches what the invoice type requires:

  · Regime-change (AFIJO / SCRAP with EsCambioRegimen='S') → all lines must be 'TEM'
  · REEXP / VEMEX                                           → all lines must be 'DEF'

Clarion mapping
---------------
Loc:Procedencia     → expected_procedure parameter ('TEM' | 'DEF')
GSQLFile2.SQL2:C2   → line.customs.origin_procedure
GSQLFile2.SQL2:C1   → line.line_number
EqiFex:TipoFactura  → invoice.invoice_type
"""

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


def review_origin_procedure(
    db: Session,
    invoice: InvoiceHeader,
    lines: List[LineItem],
    expected_procedure: str,
    errors: ErrorCollector,
) -> None:
    """
    REVISA_PROCEDENCIA_PAR
    Verifies that every export line's import origin procedure matches
    ``expected_procedure``.

    Parameters
    ----------
    db                 : active SQLAlchemy session
    invoice            : the export invoice being processed
    lines              : all line items of the invoice
    expected_procedure : 'TEM' (regime-change) or 'DEF' (REEXP / VEMEX)
    errors             : shared error collector
    """
    expected = expected_procedure.strip().upper()

    for line in lines:
        line_procedure = (
            (line.customs.origin_procedure or "").strip().upper()
            if line.customs
            else ""
        )

        if line_procedure != expected:
            errors.add_error(
                field=f"line[{line.line_number}].origin_procedure",
                message=(
                    f"La partida: {line.line_number} tiene una factura de importación "
                    f"de procedencia: '{line_procedure}', diferente a la que acepta el "
                    f"Tipo de Factura: '{invoice.invoice_type}'."
                ),
                solution=[
                    "Para Cambio de Régimen todo debe ser procedencia TEM, "
                    "para Ventas y Reexpediciones debe ser procedencia DEF."
                ],
                code="INVALID_ORIGIN_PROCEDURE",
                value={
                    "line_number": line.line_number,
                    "found": line_procedure,
                    "expected": expected,
                    "invoice_type": invoice.invoice_type,
                },
            )
