"""
Shared dataclasses for the export invoice discharge process.

Kept in a standalone module (no local imports) so that
download_balance_collector, review_series_exist, review_series_other_lines
and fill_available_balances can all import from here without circular deps.
"""

from dataclasses import dataclass, field
from decimal import Decimal
from typing import List, Optional


@dataclass
class AvailableLot:
    """
    One PEPS lot available for discharge — equivalent to one QSaldoActual record.

    Fields
    ------
    import_item_line_id : a76.item_lines.id of the import line (the lot)
    import_invoice_id   : a76.invoice_header.id of the import invoice
    part_number_id      : denormalized from the import line
    available_qty       : net balance available  (QSaldo:Cantidad); mutated by
                          compare_balances() as quantity is distributed
    consumed_qty        : how much was actually taken from this lot by
                          compare_balances(); used by register_discharge_ledger
                          to create the exact BalanceMovement amount
    value_me            : USD value of the full lot (for proportional calc)
    value_mn            : MXN value of the full lot (for proportional calc)
    order_peps          : PEPS ordering key — lower = older = consumed first
    """
    import_item_line_id: int
    import_invoice_id: int
    part_number_id: Optional[int]
    available_qty: Decimal
    value_me: Optional[Decimal]
    value_mn: Optional[Decimal]
    order_peps: int
    consumed_qty: Decimal = field(default_factory=Decimal)


@dataclass
class DownloadEntry:
    """
    Represents one export line that will be discharged from inventory.
    Equivalent to the QADesc (QueADescargar) record in the legacy system.

    Fields
    ------
    origin_procedure   : TipoMovImpo  – 'TEM' (temporal) | 'DEF' (definitiva)
    export_line        : LineaExpo    – line number on the export invoice
    part_number        : NumParte     – part number code
    class_code         : Clase        – class code
    quantity           : CantExpo     – quantity to discharge
    quantity_used      : CantUsada    – amount already consumed (starts at 0)
    unit_of_measure    : UniMed       – unit of measure code
    import_invoice     : FacturaImpo  – source import invoice number
    import_line        : LineaImpo    – source import line number
    line_item_id       : internal DB id of the LineItem (for series lookups)
    available_lots     : PEPS lots attached by fill_available_balances
    """
    origin_procedure: str
    export_line: int
    part_number: str
    class_code: str
    quantity: Decimal
    unit_of_measure: str
    import_invoice: str
    import_line: int
    line_item_id: int
    quantity_used: Decimal = field(default_factory=Decimal)
    available_lots: List[AvailableLot] = field(default_factory=list)
