"""Club convenience termination: all guaranteed unpaid installments settle atomically."""
from decimal import Decimal

from django.db import transaction
from django.utils import timezone

from club_payroll.constants import ObligationStatus
from club_payroll.models import PayrollPlan
from club_payroll.services import PayrollObligationService, PayrollSettlementService, next_plan_due
from .constants import ContractClauseStatus, ContractClauseType, ContractStatus
from .exceptions import ContractTermsError
from .models import ContractClause


def termination_quote(*, contract):
    if contract.status != ContractStatus.ACTIVE:
        raise ContractTermsError("Only active contracts can be terminated.")
    plan = PayrollPlan.objects.filter(player_contract=contract).first()
    if plan is None:
        raise ContractTermsError("Legacy contract needs an agreed compensation schedule before termination.")
    outstanding = sum((o.original_amount - o.paid_amount for o in plan.obligations.exclude(
        status__in=[ObligationStatus.CANCELLED, ObligationStatus.WAIVED, ObligationStatus.PAID]
    )), Decimal(0))
    future = Decimal(0)
    guaranteed_future = Decimal(0)
    cursor = plan.next_due_date
    # An ENDED plan can simply mean all installments were already generated.
    while cursor <= plan.end_date:
        future += plan.installment_amount
        if cursor > timezone.localdate():
            guaranteed_future += plan.installment_amount
        cursor = next_plan_due(plan, cursor)
    minimum = max(ContractClause.objects.filter(
        contract=contract, status=ContractClauseStatus.ACTIVE,
        clause_type=ContractClauseType.CLUB_TERMINATION_COMPENSATION,
        effective_from__lte=timezone.localdate(), effective_to__gte=timezone.localdate(),
    ).values_list("amount", flat=True), default=Decimal(0)) or Decimal(0)
    future_existing = sum((o.original_amount - o.paid_amount for o in plan.obligations.filter(
        due_date__gt=timezone.localdate()
    ).exclude(status__in=[ObligationStatus.CANCELLED, ObligationStatus.WAIVED, ObligationStatus.PAID])), Decimal(0))
    top_up = max(Decimal(0), minimum - guaranteed_future - future_existing)
    return {"currency": "FTG", "outstanding": str(outstanding), "ungenerated_wages": str(future),
            "clause_top_up": str(top_up), "total": str(outstanding + future + top_up),
            "calculated_at": timezone.now().isoformat()}


@transaction.atomic
def settle_club_termination(*, contract, maximum_payment=None):
    from club_payroll.exceptions import PayrollError
    from economy.exceptions import EconomyError
    from economy.services import WalletService
    from .terms import ContractTermsService

    plan = PayrollPlan.objects.select_for_update().filter(player_contract=contract).first()
    quote = termination_quote(contract=contract)
    if maximum_payment is not None:
        cap = Decimal(str(maximum_payment))
        if not cap.is_finite() or cap < 0 or Decimal(quote["total"]) > cap:
            raise ContractTermsError("Termination quote changed or exceeds the approved payment limit.")
    try:
        PayrollObligationService.generate_for_plan(plan=plan, up_to=plan.end_date)
        top_up = Decimal(quote["clause_top_up"])
        if top_up > 0:
            ContractTermsService.create_termination_compensation(
                contract=contract, source_key=f"club-decision-termination:{contract.pk}",
                amount=top_up, description="Guaranteed termination compensation top-up",
            )
        club_wallet = WalletService.get_or_create_club_wallet(club=contract.club)
        obligations = list(plan.obligations.select_for_update().exclude(
            status__in=[ObligationStatus.CANCELLED, ObligationStatus.WAIVED, ObligationStatus.PAID]
        ).order_by("pk"))
        WalletService.lock_wallets_canonically(wallets=[club_wallet, plan.recipient_wallet])
        for obligation in obligations:
            PayrollSettlementService.pay(obligation=obligation)
    except (PayrollError, EconomyError) as exc:
        raise ContractTermsError("Termination requires full payment of remaining wages and arrears; no changes were saved.") from exc
