"""Audit check 5: the Monte Carlo error of the gate statistic.

The notebook reports the gate from one seed at 10,000 paths and the front reports a within-run
standard error std(log g)/sqrt(N) of about 0.005. This runs the deployed cell at 8 seeds x 5,000
paths and compares the within-run standard error with the spread of the mean across seeds, and
decomposes the log-growth variance into the ruin atom and the body.

    cd /root/Projects/trading-framework && python3 /tmp/arena-prime-audit/candidate-2/c2_seeds.py
"""
import json
import sys

import numpy as np

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

DEC = json.load(open("/root/Projects/trading-framework/src/notebooks/reports/topics/prime_academy/paper/decision.json"))
T3 = PA.Tier(3000.0, 38.0, 51.0)
G = DEC["scenarios"]["random side, swap charged"]["cost"]
RF = DEC["scenarios"]["random side, swap charged"]["pick"]["risk"]
WAIT, H = DEC["wait"], DEC["horizon"]
N = 5000
rows = []
for s in range(1, 9):
    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)
    ru = w["paths"]["ruined"]
    rows.append(dict(seed=s, g=w["e_log_growth"], se_within=float(lg.std(ddof=1) / np.sqrt(N)), ruin=w["p_ruin"],
                     g_body=float(lg[~ru].mean()), lg_ruined_mean=float(lg[ru].mean()) if ru.any() else float("nan"),
                     n_ruined=int(ru.sum()), p10=float(np.percentile(w["paths"]["final"], 10)), med=w["med_final"], p90=float(np.percentile(w["paths"]["final"], 90))))
    r = rows[-1]
    print(f"seed {s}: g {r['g']:+.4f} se_within {r['se_within']:.4f} ruin {r['ruin']:.4f} ({r['n_ruined']} paths, mean log {r['lg_ruined_mean']:+.2f}) "
          f"body mean log {r['g_body']:+.4f}  final p10 ${r['p10']:,.0f} med ${r['med']:,.0f} p90 ${r['p90']:,.0f}")
g = np.array([r["g"] for r in rows])
print(f"\nacross 8 seeds: mean g {g.mean():+.4f}, sd of the per-seed mean {g.std(ddof=1):.4f}, mean within-run se {np.mean([r['se_within'] for r in rows]):.4f}")
print(f"ruin per seed: {[r['n_ruined'] for r in rows]} of {N}; a ruined path adds about {np.nanmean([r['lg_ruined_mean'] for r in rows]):+.2f} to the log, "
      f"so one ruined path moves the mean by {np.nanmean([r['lg_ruined_mean'] for r in rows]) / N:+.5f}")
print(f"implied se at 10,000 paths: {g.std(ddof=1) / np.sqrt(2):.4f}; the published +0.0132 is {0.0132 / (g.std(ddof=1) / np.sqrt(2)):.1f} of those from zero")
json.dump(rows, open("/tmp/arena-prime-audit/candidate-2/c2_seeds.json", "w"), indent=1)
