"""
star_exit_daily.py -- [2026-10-04] DAILY OUT-OF-SAMPLE CHECK of "bot buys, Star sells" (the user, 10/4).
After each close: for every REAL bot trade of the day, Star Follow (sf3 latest, count mode, ALL confirmed marks
as good days, lib_v2 market+gap, still-matching exit at 80) manages the sell from the bot's real buy
(same buy minute and price). Compared with the bot's real exit. Nothing live is touched.
  star_only   the bot's buy, Star's sell (pure exit comparison)
  star_rebuy  + Star's own later re-buys in those stocks that day
0.1% cost per trade on both sides. Results appended to data/playbook/star_exit_daily.jsonl.
[2026-10-08, the user, RECORD ONLY] also "star_n2": the same Star sell with the noise2 filter (Star's sell is ignored
while the close is above VWAP and the drop from the high since the buy is < 2x the normal 1-minute range = mean
high-low of the last 15 min; 24-day test +$125 vs +$100 at 0.2% cost) -- for the trade bot's AND the Star bot's
real buys (field "source").
    python3 star_exit_daily.py [DAY ...]        (default: today)
cron: 16:15 weekdays
"""
import json
import sys
from datetime import date, datetime
from pathlib import Path
from zoneinfo import ZoneInfo

import numpy as np

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

ET = ZoneInfo("America/New_York")
OUT = TRADE / "data" / "playbook" / "star_exit_daily.jsonl"
hm = lambda m: f"{9 + (30 + m) // 60}:{(30 + m) % 60:02d}"
SOURCES = {"trade_bot": TRADE, "star_bot": Path("/var/www/screener/premarket")}


def vwap_range(rows):
    """[2026-10-08] VWAP and the normal 1-minute range (mean high-low of the last 15 min) per minute."""
    by = L2._minutes(rows)
    vw, r1 = np.zeros(390), np.zeros(390)
    pv = v = 0.0; rng = []; last = 0.0
    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 = pv / v if v else c
        vw[m] = last; r1[m] = np.mean(rng[-15:]) if rng else 0.0
    return vw, r1


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


def run(day, lib, marks, wmask, nb, ns, c, source="trade_bot"):
    p = SOURCES[source] / "data" / "trades" / f"{day}_trades.jsonl"
    if not p.exists():
        print(day, "no trades file"); return None
    trades = [json.loads(l) for l in open(p)]
    trades = [t for t in trades if t.get("exit_price") and t.get("entry_time")]
    if not trades:
        print(day, "no closed trades"); return None
    d0 = datetime.fromisoformat(day).replace(tzinfo=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)
    rows, arrays, rebuy_done = {}, {}, set()
    res = []
    for t in sorted(trades, key=lambda t: t["entry_time"]):
        s = t["symbol"]
        if s not in arrays:
            ref = REF.load(day, s)
            rows_ = get(s)
            arrays[s] = L2.day_arrays(rows_, ref, day, tuple(bench)) if ref else None
            if arrays[s] is not None:
                arrays[s]["VW"], arrays[s]["R1"] = vwap_range(rows_)
        a = arrays[s]
        et = datetime.fromisoformat(t["entry_time"]).astimezone(ET)
        f = (et.hour - 9) * 60 + et.minute - 30
        bot_pl = (t["exit_price"] / t["entry_price"] - 1) * 100 - 0.1
        xt = datetime.fromisoformat(t["exit_time"]).astimezone(ET)
        r = {"day": day, "source": source, "sym": s, "buy_t": et.strftime("%H:%M"), "buy": t["entry_price"],
             "bot_sell_t": xt.strftime("%H:%M"), "bot_sell": t["exit_price"], "bot_pl": round(bot_pl, 3),
             "bot_why": (t.get("exit_reason") or "")[:60]}
        if a is None or not (5 <= f <= 384):
            r["star"] = None; res.append(r); continue
        # forced buy at minute f-1 -> position opens at minute f (the bot's buy minute); price = the bot's price
        S3.SELL_FILTER = None
        st = S3.run_day(lib, wmask, marks, nb, ns, day, a, can_buy=lambda m, f=f: m >= f - 1, force_buy_m=f - 1)
        S3.SELL_FILTER = noise2
        n2 = S3.run_day(lib, wmask, marks, nb, ns, day, a, can_buy=lambda m, f=f: m >= f - 1, force_buy_m=f - 1)
        S3.SELL_FILTER = None
        if n2:
            r.update(n2_sell_t=hm(n2[0]["sell_m"]), n2_sell=round(n2[0]["sell"], 4), n2_why=n2[0]["why"],
                     n2_pl=round((n2[0]["sell"] / t["entry_price"] - 1) * 100 - 0.1, 3))
        first = st[0] if st else None
        if first:
            sell = first["sell"]
            r.update(star_sell_t=hm(first["sell_m"]), star_sell=round(sell, 4), star_why=first["why"],
                     star_pl=round((sell / t["entry_price"] - 1) * 100 - 0.1, 3))
            if s not in rebuy_done:
                rebuy_done.add(s)
                r["star_rebuys"] = [{"buy_t": hm(x["buy_m"]), "sell_t": hm(x["sell_m"]), "pl": round(x["pl"], 3)} for x in st[1:]]
        res.append(r)
    with open(OUT, "a") as fh:
        for r in res:
            fh.write(json.dumps(r) + "\n")
    bp = sum(r["bot_pl"] for r in res if r.get("star_pl") is not None)
    sp = sum(r["star_pl"] for r in res if r.get("star_pl") is not None)
    rb = sum(x["pl"] for r in res for x in r.get("star_rebuys", []))
    n2 = sum(r["n2_pl"] for r in res if r.get("n2_pl") is not None and r.get("star_pl") is not None)
    print(f"\n{day} [{source}]: {len(res)} bot trades | bot exits {bp:+.2f}% | Star sells {sp:+.2f}% | "
          f"Star + noise2 {n2:+.2f}% | Star re-buys {rb:+.2f}%")
    for r in res:
        if r.get("star_pl") is None:
            print(f"  {r['sym']:5} {r['buy_t']} no Star data"); continue
        print(f"  {r['sym']:5} buy {r['buy_t']} {r['buy']:.2f} | bot {r['bot_sell_t']} {r['bot_pl']:+.2f}% [{r['bot_why'][:30]}] "
              f"| Star {r['star_sell_t']} {r['star_pl']:+.2f}% [{r['star_why']}]"
              + (f" | noise2 {r['n2_sell_t']} {r['n2_pl']:+.2f}%" if r.get("n2_pl") is not None else ""))
    return res


def main(days):
    c = get_client()
    lib = L2.Lib(); marks = S3.load_all(); wmask = np.array([k in marks for k in lib.keys]); nb, ns = S3.normal_rates(marks)
    S3.MIN_MATCH = 80
    for d in days:
        for src in SOURCES:
            run(d, lib, marks, wmask, nb, ns, c, src)
        REF._CACHE.clear()


if __name__ == "__main__":
    main(sys.argv[1:] or [date.today().isoformat()])
