"""
e1_test.py -- [2026-10-23] the user's E1 exit rule (from JOBY 10/23/24: give-back sold 11:35 on a 1-tick, 0.13x-volume dip with
5-min buyers 66%; the stock ran to +2.5% and the sellers only took over at 12:09-12:14).
E1 = when the 1/4 give-back fires, E1 may OVERRIDE it (hold) while the buyers are still in control; the moment E1 stops
holding and the give-back is still true (price at/under the level while under the last finished close) -> sell.
E1 reads only FINISHED bars / minutes (known live). The setup stop is never overridden; E1 never holds under the buy price.
Variants (hold while ...):
  E1a  5-min buy share >= 50%  AND NOT the last 2 finished bars both with 1-min buy share < 40%
  E1b  same with 5-min buy share >= 55%
  E1c  E1a AND the last finished bar is not a heavy seller bar (buy share < 50% on volume > 1.5x the 15-bar average)
  E1d  the dip only: peak - last close < 2 x the mean 1-min range of the last 15 bars (noise)
  E1e  E1a OR E1d
Same 833 EV3 buys (R1A R1B R4, R3 ATR 6-10%), buy at the next open, 0.2% cost; B = live give-back without E1.
    nice -n 19 python3 e1_test.py -> e1_test.log
"""
import gzip, json, sys
from collections import defaultdict
from pathlib import Path
import numpy as np
sys.path.insert(0, "/var/www/screener/trade/reports/playbook"); sys.path.insert(0, "/var/www/screener/trade")
import v2_bar_replay as R
import r1b_setup
from exit_pepg import MODS
MODS = {**MODS, "R1B": r1b_setup}
COST = 0.2; SPLIT = "2025-10-01"; HERE = Path(__file__).resolve().parent
VARS = ["B", "E1a", "E1b", "E1c", "E1d", "E1e"]


def hold(v, bars, mins, fl, j, peak):
    """E1 decision for bar j using finished bars up to j-1."""
    if v == "B":
        return False
    k = j - 1; m = mins[k]; fb, fs = fl["buy"], fl["sell"]
    def bs(mm, n):
        B = sum(fb[max(0, mm - n + 1):mm + 1]); S = sum(fs[max(0, mm - n + 1):mm + 1]); return B / (B + S) if B + S else 0.5
    def buyers(th):
        weak2 = bs(m, 1) < 0.40 and bs(mins[k - 1], 1) < 0.40
        return bs(m, 5) >= th and not weak2
    rng = sum(x["h"] - x["l"] for x in bars[max(0, k - 14):k + 1]) / min(15, k + 1)
    noise = (peak - bars[k]["c"]) < 2 * rng
    if v == "E1a": return buyers(0.50)
    if v == "E1b": return buyers(0.55)
    if v == "E1c":
        av = sum(x["v"] for x in bars[max(0, k - 15):k]) / max(1, min(15, k))
        heavy = bs(m, 1) < 0.50 and bars[k]["v"] > 1.5 * av
        return buyers(0.50) and not heavy
    if v == "E1d": return noise
    if v == "E1e": return buyers(0.50) or noise


def sim(v, bars, mins, fl, bi, P, stop, arm=1.0, g=0.25):
    peak = P; held = 0
    for j in range(bi, len(bars)):
        b = bars[j]
        if b["l"] <= stop:
            return (min(stop, b["o"]) if j > bi else stop) / P * 100 - 100 - COST, "stop", j, held
        gain = peak - P
        if gain >= P * arm / 100 and j > bi:
            x = min(peak - g * gain, bars[j - 1]["c"] * 0.9999)
            if b["l"] <= x:
                if b["l"] > P and hold(v, bars, mins, fl, j, peak):
                    held += 1
                else:
                    px = min(x, b["o"])
                    return px / P * 100 - 100 - COST, ("give-back" if not held else "E1 released"), j, held
        peak = max(peak, b["h"])
        if mins[j] >= 385:
            return b["c"] / P * 100 - 100 - COST, "15:55", j, held
    return bars[-1]["c"] / P * 100 - 100 - COST, "end", len(bars) - 1, held


def main():
    trig = defaultdict(list)
    for l in open("/var/www/screener/trade/reports/playbook/giveback_2y.jsonl"):
        t = json.loads(l)
        if t["setup"] in ("R1A", "R1B", "R4") or (t["setup"] == "R3" and 6 <= t["atr"] < 10):
            trig[t["day"]].append(t)
    rows = []
    for day in sorted(trig):
        d = json.load(gzip.open(R.OW / "bars" / f"bars_{day}.json.gz", "rt"))
        for t in trig[day]:
            s = t["sym"]; ref = R.REF.load(day, s); fl = json.loads((R.OW / "flow" / day / f"{s}.json").read_text())
            bars = [b for b in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(b["t"]) < 390]
            mins = [R.minute(b["t"]) for b in bars]
            ti = next((i for i, m in enumerate(mins) if m == t["m"]), None)
            if ti is None or ti + 1 >= len(bars):
                continue
            bi = ti + 1; P = bars[bi]["o"]
            ok, info = MODS[t["setup"]].check(bars[:ti + 1], fl, ref, t["m"])
            sup = (info or {}).get("support") or P * 0.99
            stop = min(max(sup * 0.998, P * 0.96), P * 0.995)
            r = {"setup": t["setup"], "day": day, "sym": s, "m": t["m"]}
            for v in VARS:
                pl, why, j, held = sim(v, bars, mins, fl, bi, P, stop)
                r[v] = pl; r[v + "_why"] = why; r[v + "_hold"] = mins[j] - mins[bi]; r[v + "_held"] = held
            rows.append(r)
        R.REF._CACHE.clear(); del d
    json.dump(rows, open(HERE / "e1_test.json", "w"))
    print(f"{len(rows)} EV3 trades, per trade after {COST}% cost: all (year 1 / year 2) | wins | median minutes held")
    for s in ["ALL", "R1A", "R1B", "R3", "R4"]:
        X = rows if s == "ALL" else [r for r in rows if r["setup"] == s]
        y = np.array([r["day"] < SPLIT for r in X])
        print(f" {s} ({len(X)})")
        for v in VARS:
            a = np.array([r[v] for r in X])
            print(f"   {v:4} {a.mean():+.3f}% ({a[y].mean():+.3f} / {a[~y].mean():+.3f})  win {np.mean(a > 0):.0%}  "
                  f"hold {np.median([r[v + '_hold'] for r in X]):.0f} min  total {a.sum():+.1f}%")
    print("\n exits:")
    for v in VARS:
        w = defaultdict(int)
        for r in rows:
            w[r[v + "_why"]] += 1
        print(f"   {v:4} {dict(w)}")
    j = [r for r in rows if r["sym"] == "JOBY" and r["day"] == "2024-10-23"]
    for r in j:
        print("  JOBY 10/23/24:", {v: (round(r[v], 2), r[v + "_why"], r[v + "_hold"]) for v in VARS})
    print("E1_DONE")


if __name__ == "__main__":
    main()
