"""Judge check: the gate level across seeds and the plateau's tie-break, at the deployed cell.

a. wallet_mc at 5,000 paths for seeds 1-8 (candidates 1 and 2) and 101-108 (candidate 3), one at a
   time, deployed cell: 3% assessment, 1.575% funded, cost share 3.3526%, 7-trade clock, 541 trades,
   80% honoured, $1,000 wallet on the $3,000 tier. Pools the 16 seeds.
b. the funded line search's plateau rows: is med_first_pay flat (candidate 2) or falling with risk
   (candidate 1)?
"""
import sys, time
import numpy as np

sys.path.insert(0, "/root/Projects/trading-framework-prime")
from src.notebooks.reports.topics.prime_academy.modules import prime as PA  # noqa: E402

T3 = PA.Tier(3000.0, 38.0, 51.0)
STOP = 34.791728647093755
SW = 0.004783927673690548
G = PA.cost_share(STOP) + SW
RF, WAIT, H, N = 0.01575, 7, 541, 5000
print(f"cost share {G:.4%}")

t0 = time.time()
print("== b. plateau rows (exact chain)")
rows = PA.funded_line_search(G, lo=0.006, hi=0.020, step=0.00025, wait=WAIT)
plat = PA.plateau(rows, width=0.01)
best = max(r["p_any"] for r in rows)
for r in plat:
    print(f"  risk {r['risk']:.3%} p_any {r['p_any']:.4%} med_first_pay {r['med_first_pay']} e_W {r['e_W']:.5f}")
pk = min(plat, key=lambda r: (r["med_first_pay"], -r["e_W"]))
print(f"  best p_any {best:.4%}; pick {pk['risk']:.3%}; plateau {plat[0]['risk']:.3%}..{plat[-1]['risk']:.3%}  [{time.time()-t0:.0f}s]")

print("== a. gate per seed, 5,000 paths each")
vals = {}
for s in list(range(1, 9)) + list(range(101, 109)):
    w = PA.wallet_mc(T3, 0.03, G * 0.03, 0.7, 0.8, 1000, horizon_days=H, n=N, seed=s, rr=1.0, wait=WAIT,
                     funded_risk=RF, funded_cost=G * RF, clip_up=True, clip_dn=True, paths=True)
    lg = np.log(np.maximum(w["paths"]["final"], 1.0) / 1000.0)
    vals[s] = w["e_log_growth"]
    print(f"  seed {s:3d}: g {w['e_log_growth']:+.4f} within-SE {lg.std(ddof=1)/np.sqrt(N):.4f} ruin {w['p_ruin']:.4f} "
          f"mean final ${w['mean_final']:.0f}  [{time.time()-t0:.0f}s]", flush=True)
a = np.array([vals[s] for s in range(1, 9)])
b = np.array([vals[s] for s in range(101, 109)])
c = np.concatenate([a, b])
print(f"seeds 1-8:     mean {a.mean():+.4f} sd {a.std(ddof=1):.4f} se {a.std(ddof=1)/np.sqrt(8):.4f}")
print(f"seeds 101-108: mean {b.mean():+.4f} sd {b.std(ddof=1):.4f} se {b.std(ddof=1)/np.sqrt(8):.4f}")
print(f"all 16 (80,000 paths): mean {c.mean():+.4f} sd {c.std(ddof=1):.4f} se {c.std(ddof=1)/np.sqrt(16):.4f} "
      f"t {c.mean()/(c.std(ddof=1)/np.sqrt(16)):.2f}")
# inverse-variance pool with the published 10,000-path seed-5 run (+0.0132, SE 0.0058)
se16 = c.std(ddof=1) / np.sqrt(16)
wsum = 1 / se16**2 + 1 / 0.0058**2
pooled = (c.mean() / se16**2 + 0.0132 / 0.0058**2) / wsum
print(f"pooled with published +0.0132 (SE 0.0058): {pooled:+.4f} +/- {wsum**-0.5:.4f}")
print(f"done {time.time()-t0:.0f}s")
