"""
big_losers_check.py -- [2026-10-22] the user: take the last 5 BIG LOSERS (bot buys that lost although the stock rose
>= 2% above the buy later that day) and check if everything we know now (situations S1-S9 + avoid rules + the do-not-trade
list) turns them into profit, trading the day's low-to-high swing.
  big loser = BASE replay buy (s6_test.jsonl, 2 years) with P/L <= -0.5% after the 0.2% cost AND the day's high after
              the buy >= buy x 1.02. The 5 most recent.
  each stock-day replayed 3 ways (real v2 bar replay + exit_v2):
    BASE     today's live v2 rules
    SIT      + every situation rule ON as a hold: S1, S2, S3 (in-window), S6 (3%), S8 (5% room), S9 (prev close)
    SIT+AV   SIT + the avoid rules that helped alone: min_atr_pct 8%, lower_low_by_1030, choppy_many_vs
    nice -n 19 python3 big_losers_check.py
"""
import gzip
import json
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE)); sys.path.insert(0, "/var/www/screener/trade")
import v2_bar_replay as R  # noqa: E402
import entry_situations as ES  # noqa: E402
import avoid_rules as AV  # noqa: E402
import logging  # noqa: E402
logging.getLogger("trade_bot.entry_situations").setLevel(logging.WARNING)

SIT = {"S1_window_flip": {"enabled": True, "record_only": False}, "S2_spike_confirm": {"enabled": True, "record_only": False},
       "S3_block_print": {"enabled": True, "record_only": False, "mode": "while_in_window"},
       "S6_extended": {"enabled": True, "record_only": False, "mode": "pct", "max_pct": 3.0},
       "S8_resistance": {"enabled": True, "record_only": False, "mode": "pct", "min_room_pct": 5.0},
       "S9_prev_close": {"enabled": True, "record_only": False}}
AVC = {"min_atr_pct": {"enabled": True}, "lower_low_by_1030": {"enabled": True}, "choppy_many_vs": {"enabled": True}}
CTX = {}
_orig = R.entry_v2.evaluate


def hm(m):
    return f"{9 + (30 + m) // 60}:{(30 + m) % 60:02d}"


def wrapped(sym, view, ref, f15, pers, as_of=None, cfg=None, quote=None):
    d = _orig(sym, view, ref, f15, pers, as_of=as_of, cfg=cfg, quote=quote)
    m = R.minute(as_of) - 1; day = CTX["day"]; run = CTX["run"]
    fb, fs = CTX["flow"]["buy"], CTX["flow"]["sell"]
    fm = {k: (fb[k], fs[k]) for k in range(0, m + 1)}
    ES.record(day, sym, m, d.metrics, passed=bool(d.should_enter))
    if d.should_enter:
        tags, det = ES.tag(day, sym, m, view, ref, d.metrics, cfg=SIT, flow_by_min=fm)
        det["_flowm"] = fm
        held = ES.check(day, sym, m, view, ref, d.metrics, tags, det, cfg=SIT)
        blocked, hits = AV.check(sym, view, ref, d.metrics, m + 1, cfg=AVC, v2cfg=cfg, day=None, live=False)
        CTX["sig"].append((m, tags, held, hits))
        if run != "BASE" and held:
            d.should_enter = False; CTX["held"].append((m, held[0]))
        elif run == "SIT+AV" and blocked:
            d.should_enter = False; CTX["held"].append((m, "AVOID " + blocked[0]))
    return d


R.entry_v2.evaluate = wrapped


def main():
    T = [json.loads(l) for l in open(HERE / "s6_test.jsonl")]
    B = [t for t in T if t.get("run") == "BASE"]
    cand = []
    days = {}
    for t in sorted(B, key=lambda t: (t["day"], t["buy_m"]), reverse=True):
        if t["pl_gross"] - 0.2 > -0.5:
            continue
        if t["day"] not in days:
            days[t["day"]] = json.load(gzip.open(R.OW / "bars" / f"bars_{t['day']}.json.gz", "rt"))
        bars = {R.minute(b["t"]): b for b in R.bars_of(days[t["day"]]["symbols"][t["sym"]]["bars"])}
        if t["buy_m"] not in bars:
            continue
        bp = bars[t["buy_m"]]["o"]
        hi = max(b["h"] for m, b in bars.items() if m >= t["buy_m"])
        if hi >= bp * 1.02:
            cand.append((t, bars, bp, hi))
        if len(cand) == 5:
            break
    cfg = R.get_config(); ecfg = {**(cfg.get("entry_v2") or {}), "confirm_checks": 1}; xcfg = {**(cfg.get("exit_v2") or {}), "enabled": True}
    tot = {"BASE": 0.0, "SIT": 0.0, "SIT+AV": 0.0}
    for t, bars, bp, hi in reversed(cand):
        day, s = t["day"], t["sym"]
        d = days[day]; ref = R.REF.load(day, s); flow = json.loads((R.OW / "flow" / day / f"{s}.json").read_text())
        bench = R.bench_pct(day)
        O = bars[0]["o"]; ms = sorted(m for m in bars if 15 <= m < 390)
        lo_m = min(ms, key=lambda m: bars[m]["l"]); hi_m = max(ms, key=lambda m: bars[m]["h"])
        after_lo = [m for m in ms if m >= lo_m]
        hi_after_lo = max(after_lo, key=lambda m: bars[m]["h"])
        atrp = ref["atr14"] / ref["prev_close"] * 100 if ref.get("atr14") else 0
        print(f"\n=== {day} {s}  open {O:.2f}, prev close {ref['prev_close']:.2f} (gap {(O / ref['prev_close'] - 1) * 100:+.1f}%), daily ATR {atrp:.1f}%")
        print(f"    day 9:45-16:00: low {bars[lo_m]['l']:.2f} at {hm(lo_m)}, high {bars[hi_m]['h']:.2f} at {hm(hi_m)}, close {bars[ms[-1]]['c']:.2f}; "
              f"best swing low -> later high: {bars[lo_m]['l']:.2f} -> {bars[hi_after_lo]['h']:.2f} at {hm(hi_after_lo)} "
              f"= {(bars[hi_after_lo]['h'] / bars[lo_m]['l'] - 1) * 100:+.1f}%")
        print(f"    the big loser: bought {hm(t['buy_m'])} at {bp:.2f}, {t['pl_gross'] - 0.2:+.2f}%; the stock later reached {hi:.2f} ({(hi / bp - 1) * 100:+.1f}% over the buy)")
        for run in ("BASE", "SIT", "SIT+AV"):
            CTX.update(day=day, run=run, flow=flow, sig=[], held=[])
            for z in (ES._hist, ES._pending, ES._streak, ES._c3ep, ES._s1, ES._s2, ES._s3):
                z.clear()
            tr = R.run_stock(day, s, d["symbols"][s]["bars"], flow, ref, bench, ecfg, xcfg)
            pl = sum(x["pl"] + R.COST - 0.2 for x in tr); tot[run] += pl
            print(f"    {run:7} {len(tr)} trade(s), total {pl:+.2f}%: " + ("; ".join(f"buy {hm(x['buy_m'])} {x['buy']:.2f} -> sell {hm(x['sell_m'])} {x['sell']:.2f} "
                                                                             f"{x['pl'] + R.COST - 0.2:+.2f}% [{x['why']}]" for x in tr) or "no buy"))
            if run == "BASE":
                for m, tags, held, hits in CTX["sig"]:
                    print(f"        v2 BUY {hm(m + 1)}: situations {','.join(tags) or '-'} | situation rules would hold: "
                          f"{', '.join(h.split(' ')[0] for h in held) or 'none'} | avoid hits: {', '.join(h.split(':')[0] for h in hits) or '-'}")
            else:
                hs = {}
                for m, why in CTX["held"]:
                    k = why.split(":")[0]
                    hs.setdefault(k, []).append(hm(m + 1))
                if hs:
                    print("        held: " + "; ".join(f"{k} at {', '.join(v[:4])}{'...' if len(v) > 4 else ''}" for k, v in hs.items()))
    print(f"\nTOTAL of the 5 stock-days: BASE {tot['BASE']:+.2f}% | SIT {tot['SIT']:+.2f}% | SIT+AV {tot['SIT+AV']:+.2f}%  (sum of trade %, 0.2% cost each)")


if __name__ == "__main__":
    main()
