"""Deterministic teaching example, Python 3.10+ standard library."""

def annual_working_capital(credit_sales, days_saved):
    return credit_sales * days_saved / 365


def expected_loss(exposure, probability, loss_given_default):
    return exposure * probability * loss_given_default


def reconcile_open_balance(billed, allocated, authorized_credit):
    if min(billed, allocated, authorized_credit) < 0 or allocated + authorized_credit > billed:
        raise ValueError("allocation and credit must fit the invoice")
    return billed - allocated - authorized_credit


if __name__ == "__main__":
    hours = 200 * (30 - 12) / 60
    capital = annual_working_capital(12_000_000, 5)
    added_loss = expected_loss(10_000_000, .05, .50) - expected_loss(10_000_000, .04, .50)
    assert (hours, 12 - 9, round(capital), round(added_loss)) == (60, 3, 164384, 50000)
    assert annual_working_capital(12_000_000, 0) == 0
    assert 12 - 14 == -2
    assert expected_loss(10_000_000, .06, .50) - expected_loss(10_000_000, .04, .50) == 100000
    print(f"{hours:.0f} h; {12 - 9} bp; USD {capital:.0f}; USD {added_loss:.0f}")

    # Prices are in cents. Keep weighted fills exact until the display boundary.
    total_execution_cents = 600 * 10003 + 400 * 10007
    shortfall_cents = total_execution_cents - 1_000 * 10000
    assert shortfall_cents == 4_600
    assert reconcile_open_balance(12000, 8000, 1000) == 3000
    fixed_contribution = 900 - 400 - 180
    assert fixed_contribution - round(expected_loss(10_000, .04, .50)) == 120
    assert fixed_contribution - round(expected_loss(10_000, .07, .50)) == -30
    print("Deep cases: USD 46 execution shortfall; USD 3000 open AR; USD 120 / -30 loan contribution")
