"""wallet_mc (deep wallet, p_paid=1) against the chains: cash per purchase and purchases per path.
Deployed cell: assessment 3%, funded 1.575%, wait 7, clips on, random-side swap cost."""
import numpy as np, time
from pa_imp import *
from modules import hedge as HG
g=PA.cost_share(34.791728647093755)+0.004783927673690548
T3=PA.Tier(3000,38,51); rf=0.01575; wait=7
e=PA.eval_chain(0.03,g*0.03,rr=1.0,clip_up=True,clip_dn=True)
f=PA.funded_chain(rf,g*rf,PA.payout_threshold(rf,1.0,3000,0.7),rr=1.0,clip_dn=True,wait=wait)
cash_chain=0.7*3000*e['p_pass']*f['e_W']
H=3000; n=1000
t0=time.time()
run=PA.wallet_mc(T3,0.03,g*0.03,0.7,1.0,HG.DEEP,horizon_days=H,n=n,seed=21,rr=1.0,paths=True,snap_every=1,
                 funded_risk=rf,funded_cost=g*rf,clip_up=True,clip_dn=True,wait=wait)
fl=HG.flows(run,H)
buy=np.isclose(fl,-38.0,rtol=0,atol=1e-3)
purch=buy.sum(1); cash=np.where(fl>0,fl,0).sum(1)
# purchases whose life ended before the horizon are most; truncation bias is the last account only
print(f"wallet_mc: purchases/path {purch.mean():.1f}, cash/path ${cash.mean():.0f}, cash per purchase ${cash.sum()/purch.sum():.2f}  | chain: ${cash_chain:.2f} per purchase  (n={n}, H={H}, {time.time()-t0:.0f}s)")
# pass->cash events: count of distinct payouts
pays=(fl>0).sum(1)
print(f"payouts per purchase {pays.sum()/purch.sum():.4f}  | chain: P(pass)*E[K] = {e['p_pass']*f['e_npay']:.4f}")
print(f"mean payout size ${fl[fl>0].mean():.1f}; chain E[size]*split*B = ${f['e_size']*0.7*3000:.1f}")
