"""Front, one account, 'random side, swap charged': is the ordering of 34.8 / 40 / 45 pips stable across Monte Carlo seeds?
Re-runs the front's wallet step (spread.family with k_max=1 -> hedge.shared_wallet) at each stop with the front.json inputs (cost, pace, wait, funded risk),
n=5000 paths, six seeds.  Reports T (median days to first cash), D (p90 of the year-one drawdown), ruin, log growth."""
import json, numpy as np, time
from pa_imp import *
from modules import spread as SP, hedge as HG
F=json.load(open('/root/Projects/trading-framework/src/notebooks/reports/topics/prime_academy/paper/front.json'))
cells=[c for c in F['cells'] if c['scenario']=='random side, swap charged' and c['N']==1 and (abs(c['stop']-F['stop0'])<1e-6 or c['stop'] in (40.0,45.0))]
T3=PA.Tier(3000,38,51)
rhos=SP_RHO=0.0
t0=time.time()
for c in sorted(cells,key=lambda c:c['stop']):
    H=int(round(3*365/c['pace'])); H1=int(round(365/c['pace']))
    res=[]
    for seed in (201,202,203,204,205,206):
        for k,Fl,Gt in SP.family(T3,0.0,0.03,c['cost']*0.03,0.7,1.0,H,5000,seed,k_max=1,p_paid=0.8,funded_risk=c['rf'],funded_cost=c['cost']*c['rf'],clip_up=True,clip_dn=True,wait=c['wait']):
            w=HG.shared_wallet(Fl,1000.0,Gt,paths=True); p=w.pop('paths')
            d1=HG.shared_wallet(Fl[:,:H1],1000.0,Gt[:,:H1],paths=True)['paths']['maxdd']
            t=np.where(np.isnan(p['first_cash']),np.inf,p['first_cash']+1)*c['pace']
            res.append((np.median(t),np.percentile(d1,90),np.median(d1),w['p_ruin'],w['e_log_growth'],np.mean(d1>=303),np.mean(d1>=341),np.mean(d1>=379)))
    r=np.array(res)
    print(f"stop {c['stop']:5.1f} (pace {c['pace']:.3f}, wait {c['wait']}, rf {c['rf']:.4f}): T {r[:,0].round(0)} | D p90 {r[:,1].round(0)} | ruin {np.round(r[:,3]*100,2)} | log g {np.round(r[:,4],3)}   [{time.time()-t0:.0f}s]",flush=True)
    print(f"      share of year-one drawdown >= $304 / $342 / $380 (8/9/10 fees): {r[:,5].mean():.3f} / {r[:,6].mean():.3f} / {r[:,7].mean():.3f}",flush=True)
    print(f"      means: T {r[:,0].mean():.0f}  D90 {r[:,1].mean():.0f}  logg {r[:,4].mean():+.4f} (sd of seeds {r[:,4].std(ddof=1):.4f});  front.json: T {c['T']:.0f} D {c['D']:.0f} logg {c['log_g']:+.4f}",flush=True)
