"""Financial controls at the canonical payment boundary, under wallet locks."""
from types import SimpleNamespace

from economy.exceptions import EconomyError


class ClubSpendBlocked(EconomyError):
    pass


def before_transfer(*, source, destination, amount, transaction_type, reference_type, reference_id):
    if not source.club_id:
        return
    from club_debt.services import InsolvencyRestrictionService
    from club_debt.exceptions import ClubDebtError
    from .services import BudgetService, LedgerClassificationService
    from .constants import FinanceCategory
    club = source.club
    if transaction_type in {'FRIENDLY_REFUND','MARKETPLACE_REFUND'}:
        return
    if transaction_type == 'MARKETPLACE_ESCROW':
        action = 'marketplace_buy'
        category = (FinanceCategory.FACILITY_OPEX if reference_type == 'MARKET_LEASE_RENT'
                    else FinanceCategory.MARKETPLACE_CAPEX)
    else:
        _, category = LedgerClassificationService._category(SimpleNamespace(
            source_wallet_id=source.pk,destination_wallet_id=destination.pk,
            transaction_type=transaction_type,reference_type=reference_type), source)
        action = ('discretionary_capex' if category == FinanceCategory.MARKETPLACE_CAPEX or reference_type == 'CLUB_LEVEL_UPGRADE'
                  else 'transfer_spend' if category == FinanceCategory.TRANSFER_SPEND
                  else 'friendly_stake' if transaction_type == 'FRIENDLY_RESERVE' else None)
    if action:
        try: InsolvencyRestrictionService.assert_allowed(club, action)
        except ClubDebtError as exc: raise ClubSpendBlocked(str(exc)) from exc
    # Deposits/stakes are recoverable commitments, not recognized expenses.
    if reference_type == 'MARKET_LEASE_DEPOSIT' or transaction_type == 'FRIENDLY_RESERVE':
        return
    guard = BudgetService.check_spend(club=club, category=category, amount=amount)
    if not guard['allowed']:
        raise ClubSpendBlocked(f"Club hard budget limit exceeded: {category}")


def after_transfer(entry):
    from .services import LedgerClassificationService
    for wallet in (entry.source_wallet,entry.destination_wallet):
        if wallet and wallet.club_id:
            LedgerClassificationService.classify_entry(club=wallet.club,entry=entry)
