"""Shared shift recalculation utilities — import here to avoid circular imports."""
from decimal import Decimal
from sqlalchemy.orm import Session
from .models import DailyShift, ShiftCollectionCycle, CashHandover


def recalc_shift_totals(shift_id: int, db: Session):
    """Recalculate and persist total_collected and difference on a shift.

    Sums both shift_collection_cycles AND cash_handovers linked to the shift.
    Does NOT commit — caller must db.commit() after calling this.
    """
    shift = db.query(DailyShift).filter(DailyShift.id == shift_id).first()
    if not shift:
        return

    cycles = db.query(ShiftCollectionCycle).filter(
        ShiftCollectionCycle.shift_id == shift_id
    ).all()
    handovers = db.query(CashHandover).filter(
        CashHandover.shift_id == shift_id
    ).all()

    cycle_cash   = sum(Decimal(str(c.cash_total   or 0)) for c in cycles)
    cycle_visa   = sum(Decimal(str(c.card_visa    or 0)) for c in cycles)
    cycle_amex   = sum(Decimal(str(c.card_amex    or 0)) for c in cycles)
    cycle_touch  = sum(Decimal(str(c.card_touch   or 0)) for c in cycles)
    cycle_credit = sum(Decimal(str(c.credit_total or 0)) for c in cycles)
    cycle_other  = sum(Decimal(str(c.other_income or 0)) for c in cycles)
    cycle_short  = sum(Decimal(str(c.shortage     or 0)) for c in cycles)
    cycle_adv    = sum(Decimal(str(c.advance      or 0)) for c in cycles)

    handover_cash   = sum(Decimal(str(h.calculated_total or 0)) for h in handovers)
    handover_visa   = sum(Decimal(str(h.card_visa        or 0)) for h in handovers)
    handover_amex   = sum(Decimal(str(h.card_amex        or 0)) for h in handovers)
    handover_touch  = sum(Decimal(str(h.card_touch       or 0)) for h in handovers)
    handover_credit = sum(Decimal(str(h.credit_total     or 0)) for h in handovers)

    shift.cash_collected  = round(cycle_cash   + handover_cash,          2)
    shift.card_visa       = round(cycle_visa   + handover_visa,          2)
    shift.card_amex       = round(cycle_amex   + handover_amex,          2)
    shift.card_touch      = round(cycle_touch  + handover_touch,         2)
    shift.credit_total    = round(cycle_credit + handover_credit, 2)
    shift.other_income    = round(cycle_other,                    2)
    shift.shortage        = round(cycle_short,                    2)
    shift.advance         = round(cycle_adv,                      2)

    total = (shift.cash_collected + shift.card_visa + shift.card_amex +
             shift.card_touch + shift.credit_total + shift.other_income)
    shift.total_collected = round(total, 2)
    shift.difference      = round(shift.total_sale_calc - shift.total_collected, 2)
