"""Reproduce the twenty illustrative scenarios; no external account access."""
from pathlib import Path
import csv,json,math

def payment(principal, rate, years):
    if principal < 0 or rate < 0 or years <= 0:
        raise ValueError('Principal/rate must be nonnegative and years positive')
    months=years*12
    if rate == 0: return principal/months
    r=rate/12
    return principal*r/(1-(1+r)**(-months))

def build():
    rows=[]
    for price in [500000,1000000,2000000,3000000]:
        for code in range(1,6):
            wc=price*(.125 if code==4 else .075)
            fees=price*(.04 if code==4 else .025)
            project=price+wc+fees
            eqrate=.15 if code==3 else .10
            injection=project*eqrate
            standby=injection*.5 if code==2 else 0
            seller=project*.1 if code==5 else 0
            buyer=injection-standby
            senior=project-buyer-standby-seller
            closing=price*.015
            paid=price*.01
            retained=price*(.08 if code==5 else .04)
            due=buyer+closing
            resources=due+paid+retained
            service=12*(payment(senior,.10,10)+payment(seller,.08,10))
            cf=price*.20
            assert math.isclose(senior+buyer+standby+seller,project)
            rows.append(dict(scenario=f'{price//1000}K-M{code}',purchase_price=price,configuration=f'M{code}',working_capital=wc,project_costs=fees,total_project_uses=project,assumed_contribution_rate=eqrate,required_contribution=injection,buyer_contribution=buyer,qualifying_standby_seller=standby,ordinary_seller_debt=seller,senior_debt=senior,unfinanced_closing_costs=closing,previously_paid_costs=paid,retained_liquidity=retained,cash_due_at_closing=due,total_buyer_resources=resources,assumed_cash_flow=cf,annual_debt_service=service,dscr=cf/service,dscr_earnings_down_10pct=cf*.9/service,dscr_senior_rate_12pct=cf/(12*(payment(senior,.12,10)+payment(seller,.08,10)))))
    assert len(rows)==20
    return rows

if __name__=='__main__':
    assert payment(120000,0,10)==1000
    result=build()
    here=Path(__file__).resolve().parent
    (here/'cash-scenarios.json').write_text(json.dumps(result,indent=2))
    with (here/'cash-scenarios.csv').open('w',newline='') as f:
        w=csv.DictWriter(f,fieldnames=result[0]);w.writeheader();w.writerows(result)
    print('Generated 20 illustrative scenarios; all sources equal uses.')
