"""Accounts that refuse what they cannot do by raising exceptions their callers handle."""

from dataclasses import dataclass

from verada import Natural, ensures, old, raises, requires, result, terminates


class InsufficientFunds(Exception):
    pass


class AccountFrozen(Exception):
    pass


class TooManySteps(Exception):
    pass


@dataclass
class Account:
    balance: Natural = 0
    frozen: bool = False


def deposit(a: Account, amount: Natural) -> None:
    requires(a.balance <= Natural.last - amount)
    ensures(a.balance == old(a.balance) + amount and a.frozen == old(a.frozen))
    a.balance = a.balance + amount


@terminates
def withdraw(a: Account, amount: Natural) -> None:
    ensures(a.balance == old(a.balance) - amount and a.frozen == old(a.frozen))
    # (an account may be passed by copy, so what a raise promises is about it on entry)
    raises({InsufficientFunds: not old(a.frozen) and amount > old(a.balance),
            AccountFrozen: old(a.frozen)})
    if a.frozen:
        raise AccountFrozen
    elif amount > a.balance:
        raise InsufficientFunds("not enough money")
    a.balance = a.balance - amount


# a function never propagates: it handles what the procedures it calls raise
def can_withdraw(balance: Natural, amount: Natural) -> bool:
    ensures(result == (amount <= balance))
    trial = Account(balance=balance, frozen=False)
    try:
        withdraw(trial, amount)
        return True
    except InsufficientFunds:
        return False
    except AccountFrozen:
        return False
