"""
star_sell_dip_test.py -- [2026-10-08] The user (ANGO / WULF 10/8: Star sold on a small dip, both rose after):
does a filter on Star's sells help? Same setup as star_sell_variants.py (24 days, bot buys = first v2 signal per
stock, Star sells, $1,640 per trade), now with the live 3% safety stop, scored at 0.1% AND the real ~0.2% cost.
  base       Star sells as live
  swingN     Star's sell counts only if the close breaks below the lowest low of the previous N minutes
             (the last pullback low); N = 5, 10, 15
  noiseK     Star's sell is ignored while the close is above VWAP AND the drop from the high since the buy is
             < K x the normal 1-minute range (mean high-low of the last 15 min); K = 1, 2, 3
  sw10vw     sell only if the close breaks the 10-min low OR is below VWAP
Plus the late-buy question: P/L of buys before / after 14:30 (24 days here, 2 years from v2_bar_replay).
    python3 star_sell_dip_test.py
"""
import json
import sys
from datetime import datetime
from pathlib import Path

import numpy as np

sys.argv.append("--allmarks")
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE)); sys.path.insert(0, "/var/www/screener/trade")
import sf3_batch as S3
import star_takeover as ST
import lib_v2 as L2
import reference as REF
from alpaca_client import get_client


def swing(n):
    return lambda a, pos, m: a["C"][m] < a["L"][max(0, m - n):m].min()


def noise(k):
    return lambda a, pos, m: not (a["C"][m] >= a["VW"][m] and pos["high"] - a["C"][m] < k * a["R1"][m])


VAR = {"base": None, "swing5": swing(5), "swing10": swing(10), "swing15": swing(15),
       "noise1": noise(1), "noise2": noise(2), "noise3": noise(3),
       "sw10vw": lambda a, pos, m: a["C"][m] < a["L"][max(0, m - 10):m].min() or a["C"][m] < a["VW"][m]}
LATE = 300   # 14:30


def extra(rows):
    """VWAP and normal 1-minute range (mean high-low of the last 15 minutes) per minute 0..389."""
    by = L2._minutes(rows)
    vw, r1 = np.zeros(390), np.zeros(390)
    pv = v = 0.0; rng = []; last_vw = None
    for m in range(390):
        if m in by:
            _, o, h, l, c, vol = by[m][:6]
            pv += (h + l + c) / 3 * vol; v += vol; rng.append(h - l)
            last_vw = pv / v if v else c
        vw[m] = last_vw if last_vw is not None else 0
        r1[m] = np.mean(rng[-15:]) if rng else 0
    return vw, r1


def summary(name, T, days, cost):
    half = days[len(days) // 2]
    p = np.array([t["gross"] - cost for t in T]) if T else np.zeros(0)
    h = np.array([t["day"] < half for t in T], bool)
    return (f"{name:8}: {len(p):3} trades, win {(p > 0).mean() if len(p) else 0:.0%}, total ${p.sum() * 16.4:+8.2f} "
            f"(halves ${p[h].sum() * 16.4:+.0f} / ${p[~h].sum() * 16.4:+.0f}), median held "
            f"{np.median([t['held'] for t in T]) if T else 0:.0f} min, stops {sum(t['why'] == 'safety stop' for t in T)}")


def main():
    days = sorted(p.name[15:25] for p in ST.OUT.glob("entry1002_live_*.out"))
    c = get_client()
    lib = L2.Lib(); m3 = S3.load(); wmask = np.array([k in m3 for k in lib.keys]); nb, ns = S3.normal_rates(m3)
    S3.MIN_MATCH = 80; S3.SAFETY_STOP = 3.0
    R = {v: [] for v in VAR}
    for day in days:
        first = {}
        for t in ST.bot_trades(day):
            first[t["sym"]] = min(first.get(t["sym"], 999), t["buy_m"])
        d0 = datetime.fromisoformat(day).replace(tzinfo=ST.ET)
        get = lambda s: [[x.timestamp, float(x.open), float(x.high), float(x.low), float(x.close), float(x.volume)]
                         for x in c.get_minute_bars(s, start=d0.replace(hour=9, minute=30), end=d0.replace(hour=16), limit=1000)]
        bench = []
        for b in ("SPY", "IWM"):
            by = L2._minutes(get(b)); arr = np.zeros(390, np.float32); o = by[min(by)][1]; last = o
            for m in range(390):
                last = by[m][4] if m in by else last; arr[m] = (last / o - 1) * 100
            bench.append(arr)
        for s, f in first.items():
            ref = REF.load(day, s)
            rows = get(s)
            a = L2.day_arrays(rows, ref, day, tuple(bench)) if ref else None
            if a is None:
                continue
            a["VW"], a["R1"] = extra(rows)
            for v, flt in VAR.items():
                S3.SELL_FILTER = flt
                for t in S3.run_day(lib, wmask, m3, nb, ns, day, a, can_buy=lambda m, f=f: m >= f, force_buy_m=f):
                    t["gross"] = t["pl"] + S3.COST
                    R[v].append({"day": day, "sym": s, **t})
        REF._CACHE.clear()
        print(day, {v: round(sum(t["gross"] - 0.1 for t in T if t["day"] == day) * 16.4, 1) for v, T in R.items()}, flush=True)
    S3.SELL_FILTER = None
    for cost in (0.1, 0.2):
        print(f"\n{len(days)} days, $1,640 per trade, {cost}% cost, 3% safety stop")
        for v, T in R.items():
            print(summary(v, T, days, cost))
    print("\nlate buys (24 days, base, 0.2% cost):")
    for lab, sel in (("before 14:30", lambda t: t["buy_m"] <= LATE), ("after 14:30", lambda t: t["buy_m"] > LATE)):
        print(" ", summary(lab, [t for t in R["base"] if sel(t)], days, 0.2))
    # the bot's own exits over 2 years
    T2 = [json.loads(l) for l in open(HERE / "v2_bar_replay_2024-10-01_2026-10-02.jsonl")]
    print("\nlate buys, 2-year v2 replay (bot buys + bot exits), per trade at 0.2% cost:")
    for lo, hi, lab in ((0, 90, "09:30-11:00"), (90, 180, "11:00-12:30"), (180, 270, "12:30-14:00"),
                        (270, 300, "14:00-14:30"), (300, 330, "14:30-15:00"), (330, 390, "15:00-16:00")):
        for yr, sel in (("y1", lambda t: t["day"] < "2025-10-01"), ("y2", lambda t: t["day"] >= "2025-10-01")):
            g = np.array([(t["sell"] / t["buy"] - 1) * 100 - 0.2 for t in T2 if lo <= t["buy_m"] < hi and sel(t)])
            print(f"  {lab} {yr}: {len(g):4} trades, {g.mean() if len(g) else 0:+.3f}%/trade, win {(g > 0).mean() if len(g) else 0:.0%}")


if __name__ == "__main__":
    main()
