#!/usr/bin/env python3
"""Verify the five published hypothetical examples; no network or trading access."""
import csv,json,math
from pathlib import Path

ROOT=Path(__file__).resolve().parent
def near(actual,expected):
    assert math.isclose(actual,expected,rel_tol=1e-10,abs_tol=1e-8),(actual,expected)
def read(kind):
    record=json.loads((ROOT/(kind+'.json')).read_text())
    assert record['observedTrades'] is False and record['observedQuotes'] is False
    rows=list(csv.DictReader((ROOT/(kind+'.csv')).open()))
    values={r['field']:r['value'] for r in rows}
    for k,v in record['calculatorDefaults'].items():
        if isinstance(v,(float,int)):near(float(values[k]),v)
        else:assert values[k]==v
    assert record['sources'] and record['calculatorAssumptions']
    return record['calculatorDefaults']

x=read('exit')
a=x['quantity']*x['priceA']*(1-x['feeA']/100)*x['rateA']-x['costA']
b=x['quantity']*x['priceB']*(1-x['feeB']/100)*x['rateB']-x['costB']
near(a,4345.955);near(b,4346.5);assert b>a
x=read('liquidation')
for lev in (3,5,10):
    threshold=x['entry']*(1-1/lev)/(1-(x['mmr']+x['fee'])/100)
    # Independently recompute against exact rational parameters, not rounded article cells.
    exact=(50000*(1-1/lev))/(1-0.005-0.00045)
    near(threshold,exact)
    assert (x['low']<threshold)==(lev==10)
x=read('rand')
start=x['btcStart']*x['fxStart']*(1+x['premiumStart']/100)
end=x['btcEnd']*x['fxEnd']*(1+x['premiumEnd']/100)
near(100*(end/start-1),-12)
for rate,sats in [(1.6,98400),(.35,99650),(.18,99820)]:
    near(x['budget']/x['price']*(1-rate/100)*1e8,sats)
x=read('arbitrage')
net=x['quantity']*(x['sell']*(1-x['sellFee']/100)-x['buy']*(1+x['buyFee']/100))-x['restore']-x['overhead']
near(net,5.963)
stress=x['quantity']*(10.16*(1-x['sellFee']/100)-x['buy']*(1+x['buyFee']/100))-x['restore']-x['overhead']
near(stress,-7.024)
x=read('prop');daily=x['dayBalance']*.97;total=x['initial']*.94
near(daily,9700);near(total,9400)
for q,breach,finish in [(.1,False,10095.96),(.2,True,None)]:
    opened=x['dayBalance']-q*x['entry']*x['fee']/100
    low=opened+q*(x['low']-x['entry'])
    assert (low<=max(daily,total))==breach
    if breach:near(x['entry']+(max(daily,total)-opened)/q,48520)
    else:near(opened+q*(x['close']-x['entry'])-q*x['close']*x['fee']/100,finish)
print('PASS: five hypothetical models, CSV/JSON input agreement, and source/model labels.')
