"""
fade_switch_test.py -- [2026-10-23] the user: "keep GB2 till the price and buy share start to fade and the sellers take over,
then switch to GB1". GB2 = 1/4 give-back armed at +2%; GB1 = armed at +1%. The switch reads FINISHED bars only:
  F1  FADE = price falling (last close < the close 3 bars before) AND buy share fading (5-min buy share >= 10 points under
      its value 5 bars before) AND sellers taking over (5-min buy share < 50%). Once seen -> GB1 for the rest of the trade.
  F2  F1 but not latched: back to GB2 when the fade is gone
  F3  F1 with stronger sellers: 5-min buy share < 45% AND the last 1-min bar < 40% buyers
  F4  F1 where "price falling" = the close under VWAP or under the two closes before
  F5  F1 + the sellers come with volume: the last bar's volume >= its 15-bar average
  F6  F1 but the fade only counts after the trade has been up >= 1% (a dip right after the buy is ignored)
Reference GB1, GB2. 833 EV3 buys and the 535 kept by N2+N3, 0.2% cost, year 1 / year 2.
"""
import gzip, json, sys
from collections import defaultdict
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"
VARS = ["GB1", "GB2", "F1", "F2", "F3", "F4", "F5", "F6"]


def bs(fl, m, n):
    B = sum(fl["buy"][max(0, m - n + 1):m + 1]); S = sum(fl["sell"][max(0, m - n + 1):m + 1]); return B / (B + S) if B + S else 0.5


def fade(v, bars, mins, fl, k, vw):
    if k < 6:
        return False
    m = mins[k]; s5 = bs(fl, m, 5); s5a = bs(fl, mins[k - 5], 5)
    if v == "F4":
        down = bars[k]["c"] < vw or (bars[k]["c"] < bars[k - 1]["c"] < bars[k - 2]["c"])
    else:
        down = bars[k]["c"] < bars[k - 3]["c"]
    sellers = s5 < 0.50
    if v == "F3":
        sellers = s5 < 0.45 and bs(fl, m, 1) < 0.40
    ok = down and (s5a - s5) >= 0.10 and sellers
    if ok and v == "F5":
        w = bars[max(0, k - 15):k]
        ok = bars[k]["v"] >= sum(x["v"] for x in w) / len(w)
    return ok


def sim(v, bars, mins, fl, bi, P, stop):
    peak = P; latched = False
    pv = sum((x["h"] + x["l"] + x["c"]) / 3 * x["v"] for x in bars[:bi]); cv = sum(x["v"] for x in bars[:bi]); vws = []
    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
        if j > bi:
            gain = peak - P
            if v == "GB1": arm = 1.0
            elif v == "GB2": arm = 2.0
            else:
                f = fade(v, bars, mins, fl, j - 1, vws[-1])
                if v == "F6" and peak < P * 1.01:
                    f = False
                if v == "F2":
                    arm = 1.0 if f else 2.0
                else:
                    latched = latched or f
                    arm = 1.0 if latched else 2.0
            if gain >= P * arm / 100:
                x = min(peak - 0.25 * gain, bars[j - 1]["c"] * 0.9999)
                if b["l"] <= x:
                    return min(x, b["o"]) / P * 100 - 100 - COST, ("give-back GB1" if arm == 1.0 else "give-back GB2"), j
        peak = max(peak, b["h"])
        pv += (b["h"] + b["l"] + b["c"]) / 3 * b["v"]; cv += b["v"]; vws.append(pv / cv if cv else b["c"])
        if mins[j] >= 385:
            return b["c"] / P * 100 - 100 - COST, "15:55", j
    return bars[-1]["c"] / P * 100 - 100 - COST, "end", len(bars) - 1


nt = {(r["day"], r["sym"], r["m"]): (r["f"]["N2"] or r["f"]["N3"]) for r in json.load(open("notrade.json"))}
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"], "nt": nt.get((day, s, t["m"]), False)}
        for v in VARS:
            pl, why, j = sim(v, bars, mins, fl, bi, P, stop)
            r[v] = pl; r[v + "_t"] = mins[j]; r[v + "_why"] = why
        rows.append(r)
    R.REF._CACHE.clear(); del d
json.dump(rows, open("fade_switch.json", "w"))
for lab, X in (("ALL 833", rows), ("kept by N2+N3", [r for r in rows if not r["nt"]])):
    y = np.array([r["day"] < SPLIT for r in X])
    print(f"\n{lab}: {len(X)} buys, per trade after 0.2% cost (year 1 / year 2)")
    for v in VARS:
        a = np.array([r[v] for r in X])
        sw = np.mean([r[v + "_why"] == "give-back GB1" for r in X]) if v[0] == "F" else 0
        print(f"   {v:4} {a.mean():+.3f}% ({a[y].mean():+.3f} / {a[~y].mean():+.3f})  win {np.mean(a > 0):.0%}  total {a.sum():+.1f}%"
              + (f"  | sold by GB1 after a switch: {sw:.0%}" if v[0] == "F" else ""))
    if lab != "ALL 833":
        for st in ("R1A", "R1B", "R3", "R4"):
            Z = [r for r in X if r["setup"] == st]
            print(f"     {st} ({len(Z)}): " + "  ".join(f"{v} {np.mean([r[v] for r in Z]):+.3f}" for v in VARS))
hm = lambda m: f"{9 + (30 + m) // 60}:{(30 + m) % 60:02d}"
for r in rows:
    if (r["sym"], r["day"]) in (("HELP", "2025-07-03"), ("JOBY", "2024-10-23"), ("DERM", "2024-11-05"), ("QUBT", "2025-05-20")):
        print(f"  {r['sym']} {r['day']} m{r['m']}: " + " ".join(f"{v} {r[v]:+.2f}@{hm(r[v + '_t'])}" for v in VARS))
print("FADE_DONE")
