"""exit_compare.py -- [2026-09-27] same fixed entries, different exits, vs held to 15:55."""
import json, statistics as st, sys
from datetime import datetime
DW = {(r["date"], r["symbol"]): r for r in json.load(open("/var/www/screener/trade/reports/open_window/daily_winners.json"))}
held = {(d, t["symbol"]): t for d, x in json.load(open("data/simulations/entry_rules_21d.json"))["days"].items() for t in x["trades"]}
for path in sys.argv[1:]:
    r = json.load(open(path))
    tr = [(d, t) for d, x in r["days"].items() for t in x["trades"]]
    pl = sum(t["pl_dollars"] for _, t in tr); w = sum(t["pl_dollars"] > 0 for _, t in tr)
    hl = [(d, t) for d, t in tr if held[(d, t["symbol"])]["pl_dollars"] <= 0]
    hw = [(d, t) for d, t in tr if held[(d, t["symbol"])]["pl_dollars"] > 0]
    big = [(d, t) for d, t in tr if DW[(d, t["symbol"])]["open_close_pct"] >= 5]
    hold_min = [(datetime.fromisoformat(t["exit_time"]) - datetime.fromisoformat(t["entry_time"])).total_seconds() / 60 for _, t in tr]
    print(f"\n== {r['name']}: {len(tr)} trades, {w} winners ({w/len(tr)*100:.0f}%), net ${pl:+.0f}, median hold {st.median(hold_min):.0f} min")
    print(f"   the 309 held-losers : now ${sum(t['pl_dollars'] for _, t in hl):+.0f} (held: ${sum(held[(d,t['symbol'])]['pl_dollars'] for d,t in hl):+.0f}); "
          f"{sum(t['pl_dollars'] > 0 for _, t in hl)} turned positive, {sum(-10 < t['pl_dollars'] <= 0 for _, t in hl)} cut to a loss under $10")
    print(f"   the 311 held-winners: now ${sum(t['pl_dollars'] for _, t in hw):+.0f} (held: ${sum(held[(d,t['symbol'])]['pl_dollars'] for d,t in hw):+.0f}); "
          f"{sum(t['pl_dollars'] <= 0 for _, t in hw)} ended at a loss or flat")
    print(f"   big winners picked ({len(big)}): now ${sum(t['pl_dollars'] for _, t in big):+.0f} (held: ${sum(held[(d,t['symbol'])]['pl_dollars'] for d,t in big):+.0f})")
    reasons = {}
    for _, t in tr:
        e = t["exit_reason"]
        k = ("original stop" if "(entry stop)" in e else "breakeven step" if "breakeven" in e else
             "first-reversal breakeven" if "first reversal" in e else "trail (2x 1-min ATR)" if "trail" in e else
             "later step (+R)" if "step" in e else "end of day" if "END_OF_DAY" in e else e[:40])
        reasons.setdefault(k, []).append(t["pl_dollars"])
    for k, v in sorted(reasons.items(), key=lambda kv: -len(kv[1])):
        print(f"   exit by {k:42} {len(v):4} trades  ${sum(v):+8.0f}")
