"""
analyze.py -- [2026-09-26] results of run_tick20.sh (20-day tick replay):
setup J vs J + entry_rules PASS gate vs gate with 15-min lockout, per day
and per trade, plus the shadow-feature study on J's own snapshots
(labeled from the 20-day 1-min bars).
"""
import glob
import json
import sys
from collections import defaultdict
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parent))
import shadow_analysis as sa

SIM = Path("/var/www/screener/trade/data/simulations")
VARIANTS = {"base": "", "gate": "_gatepass", "gate15": "_gatepass_gb15"}


def load_trades(v):
    out = {}
    for f in sorted(glob.glob(str(HERE / "cands" / "*.json"))):
        d = Path(f).stem
        p = SIM / f"{d}_sim_maxpos99_gr_r25_es0p_rs45_plan_ctx_rr20_rt1_ext_msk25{VARIANTS[v]}_cf.json"
        if p.exists():
            out[d] = json.load(open(p))["trades"]
    return out


def main():
    res = {v: load_trades(v) for v in VARIANTS}
    days = sorted(res["base"])
    print(f"{len(days)} days replayed\n")
    print(f"{'day':12}" + "".join(f"{v:>22}" for v in VARIANTS))
    tot = defaultdict(lambda: [0, 0, 0.0])
    for d in days:
        row = f"{d:12}"
        for v in VARIANTS:
            tr = res[v].get(d)
            if tr is None:
                row += f"{'-':>22}"; continue
            pl = sum(t["pl_dollars"] for t in tr); w = sum(t["pl_dollars"] > 0 for t in tr)
            tot[v][0] += len(tr); tot[v][1] += w; tot[v][2] += pl
            row += f"{f'{len(tr)}t {w}W ${pl:+.2f}':>22}"
        print(row)
    print("-" * 78)
    print(f"{'TOTAL':12}" + "".join(f"{f'{n}t {w}W ${pl:+.2f}':>22}" for n, w, pl in tot.values()))
    for v, (n, w, pl) in tot.items():
        if n:
            print(f"  {v:7} win rate {w/n*100:.0f}%  avg ${pl/n:+.2f}/trade")

    print("\nJ trades and what the gate did with them:")
    for d in days:
        for t in res["base"][d]:
            kept = {v: any(g["symbol"] == t["symbol"] and g["entry_time"] == t["entry_time"]
                           for g in res[v].get(d, [])) for v in ("gate", "gate15")}
            print(f"  {d} {t['symbol']:6} {t['entry_time'][11:19]} ${t['pl_dollars']:+8.2f}  "
                  f"gate:{'kept' if kept['gate'] else 'BLOCKED/moved'}  gate15:{'kept' if kept['gate15'] else 'BLOCKED/moved'}"
                  f"  ({t.get('exit_reason', '')[:45]})")
    print("\nTrades the gated runs took that J did not (delayed / different entries):")
    for v in ("gate", "gate15"):
        for d in days:
            for g in res[v].get(d, []):
                if not any(t["symbol"] == g["symbol"] and t["entry_time"] == g["entry_time"] for t in res["base"][d]):
                    print(f"  {v:6} {d} {g['symbol']:6} {g['entry_time'][11:19]} ${g['pl_dollars']:+8.2f}")

    d = HERE / "shadow_base"
    if d.exists():
        snaps, outs = sa.load(d, sa.bar_source())
        trades = [t for tr in res["base"].values() for t in tr]
        for t in trades:
            t["pl"] = t["pl_dollars"]
        sa.report("20-day TICK replay, setup J (full order-flow features)", snaps, outs, trades)


if __name__ == "__main__":
    main()
