from sqlalchemy.orm import Session
from api.v1.modules.a76.invoices.models import InvoiceFinancials, InvoiceHeader, InvoiceLogistics
from core.exceptions import ErrorCollector

from .. import schemas



def apply_calculations(
    invoice: schemas.InvoiceHeaderUpdate,
):
    if invoice.compliance_mx:
        if invoice.invoice_type == "CR":
            invoice.compliance_mx.is_regime_change = True
        else:
            invoice.compliance_mx.is_regime_change = False
            
    if invoice.financials:
        # Arithmetica defensiva: (val or 0)
        freight = invoice.financials.freight or 0
        insurance = invoice.financials.insurance or 0
        packaging = invoice.financials.packaging or 0
        other = invoice.financials.other_increments or 0
        increments_me = freight + insurance + packaging + other
        
        # Tipo de cambio seguro
        tc = invoice.financials.exchange_rate or 1 # Fallback a 1 para evitar division por cero
        
        if invoice.financials.currency == "foreign":
            invoice.financials.total_increments_me = increments_me
            invoice.financials.total_increments_mn = increments_me * tc
            invoice.financials.currency_type = "USD"
        elif invoice.financials.currency == "local":
            invoice.financials.total_increments_mn = increments_me
            invoice.financials.total_increments_me = increments_me / tc if tc != 0 else 0
            invoice.financials.currency_type = "MXN"
        elif invoice.financials.currency == "manual":
            # TC_MM para moneda manual
            tc_mm = invoice.financials.exchange_rate_mm or 1
            invoice.financials.total_increments_me = increments_me / tc_mm if tc_mm != 0 else 0
            invoice.financials.total_increments_mn = invoice.financials.total_increments_me * tc
            
    if invoice.compliance_mx:
        invoice.compliance_mx.is_pedimento_pending = False
        if not invoice.compliance_mx.pedimento_id:
            invoice.compliance_mx.is_pedimento_pending = True
        
    
        
   