"""The purchase gate: noise, and the value of each input at which expected log growth (80% honoured, $1,000, $3,000 tier) flips sign.
wallet_mc with n=5000 paths (the brief's cap), common random numbers (same seed) across a sweep so differences are smooth."""
import sys, time, numpy as np
from pa_imp import *
T3=PA.Tier(3000,38,51)
STOP=34.791728647093755; SW=0.004783927673690548
G0=PA.cost_share(STOP)+SW           # random side, swap charged
RF=0.01575; WAIT=7; H0=541; N=5000
def gate(g=G0, honour=0.8, rf=RF, wait=WAIT, H=H0, seed=13, W0=1000, ra=0.03, n=N, **kw):
    w=PA.wallet_mc(T3,ra,g*ra,0.7,honour,W0,horizon_days=H,n=n,seed=seed,rr=1.0,wait=wait,funded_risk=rf,funded_cost=g*rf,clip_up=True,clip_dn=True,paths=True,**kw)
    lg=np.log(np.maximum(w['paths']['final'],1.0)/W0)
    return w['e_log_growth'], lg.std(ddof=1)/np.sqrt(n), w['p_ruin'], w['mean_final']
def P(*a): print(*a,flush=True)
t0=time.time()
P("== a. Monte Carlo noise at the deployed cell (random side, swap, 80%)")
vals=[]
for s in range(1,9):
    m,se,ru,mf=gate(seed=100+s); vals.append(m); P(f"seed {100+s}: e_log_growth {m:+.4f} (within-run SE {se:.4f}) ruin {ru:.3%} mean final ${mf:.0f}")
P(f"across 8 seeds of 5,000: mean {np.mean(vals):+.4f}, sd {np.std(vals,ddof=1):.4f}, min {min(vals):+.4f}, max {max(vals):+.4f}; t of the mean {np.mean(vals)/(np.std(vals,ddof=1)/np.sqrt(8)):.1f}  [{time.time()-t0:.0f}s]")
P("== b. honour rate (iid per request, refused request still resets equity)")
for h in (1.0,0.9,0.85,0.8,0.75,0.7,0.65,0.6,0.5,0.0):
    m,se,ru,mf=gate(honour=h); P(f"honour {h:.2f}: {m:+.4f} (SE {se:.4f}) ruin {ru:.3%}")
P(f"[{time.time()-t0:.0f}s]")
P("== c. cost share of risk (funded risk held at 1.575%)")
for g in (0.0287,0.031,0.0335264,0.0345,0.036,0.0375,0.04,0.045,0.05):
    m,se,ru,mf=gate(g=g); P(f"cost share {g:.4%}: {m:+.4f} (SE {se:.4f}) ruin {ru:.3%}")
P(f"[{time.time()-t0:.0f}s]")
P("== d. payout clock in trades (CRN)")
for w in (5,6,7,8,9,10,14):
    m,se,ru,mf=gate(wait=w); P(f"wait {w}: {m:+.4f} (SE {se:.4f})")
P("== e. horizon in trades (3 years = 541)")
for H in (150,250,350,450,541,700,900,1200):
    m,se,ru,mf=gate(H=H); P(f"H {H} trades ({H*2.025/365:.2f} y): {m:+.4f} (SE {se:.4f})")
P(f"[{time.time()-t0:.0f}s]")
