"""
REVISA_COSTOS_0
Validates that every principal line item (non sub-item) of an export invoice
has a unit cost greater than zero.

A zero unit cost on a principal line is an error because values and customs
declarations cannot be computed without it.

Legacy equivalent
-----------------
SELECT COUNT(*) FROM QEqeMaq EqiPex
WHERE  EqiPex.Consecutivo          = <invoice.id>
  AND  EqiPex.CostoUnitarioCaptura = 0
  AND  EqiPex.EsSubPartida         = 'P'   -- 'P' = Principal (not a sub-item)
"""

from decimal import Decimal
from typing import List

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


def review_unit_cost(
    lines: List[LineItem],
    errors: ErrorCollector,
) -> None:
    """
    REVISA_COSTOS_0

    For every principal line (``fa_data.is_subitem`` is False or None) checks
    that ``financial.unit_cost_capture`` is not zero.  Adds a COSTO_CERO error
    for each offending line.

    Sub-items are skipped because their cost derives from the principal line
    and may legitimately be zero at this stage.
    """
    for line in lines:
        # Skip sub-items — EsSubPartida = 'P' means is_subitem is False/None
        is_subitem = line.fa_data.is_subitem if line.fa_data else False
        if is_subitem:
            continue

        unit_cost = (
            line.financial.unit_cost_capture
            if line.financial
            else None
        )
        if unit_cost is not None and unit_cost != Decimal(0):
            continue

        errors.add_error(
            field=f"line[{line.line_number}].unit_cost_capture",
            message=f"La partida: {line.line_number} no tiene capturado el costo unitario",
            solution=[
                f"Asignar el costo unitario a la partida: {line.line_number}, "
                "o desactivar el parámetro de En Base al Costo de Captura."
            ],
            code="COSTO_CERO",
        )
