"""
star_takeover.py -- [2026-10-03] "BOT SELECTS, STAR TAKES OVER" (the user, 2026-10-03).
The bot's v2 buy signal (every-signal tick replay, reports/open_window/tick20/out/entry1002_live_<day>.out,
24 days 8/27-9/30, 9:28 lists) SELECTS a stock at the minute of its first v2 buy. Then:
  A  STAR TIMES IT   Star Follow latest (sf3 count mode, winners-only, lib_v2 market+gap, still-matching
                     exit at 80) may buy from that minute on with its own buy signal, sells on its own exit,
                     may trade the stock again later that day
  B  BOT BUYS, STAR SELLS   buy at the next minute's open after the bot's buy minute, Star Follow manages
                     the sell (and may re-buy later on its own signal)
  BOT                the bot's own trades (v2 + live exits), same replay
All three through the same 5-slot filter (first come first served by buy time) and the same size,
$1,640 per trade (19% of $8,631; the bot's size is capped there too). 0.1% cost per Star trade
(the bot's replay P/L is before costs, so 0.1% is taken off it too).
    python3 star_takeover.py
"""
import json
import re
import sys
from datetime import 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 / "reports/open_window/tick20/out"
SIZE, SLOTS = 1640.0, 5
LINE = re.compile(r"\s+(\d\d):(\d\d):\d\d (\S+)\s+BUY.*?-> (\d\d):(\d\d):\d\d SELL.*?P/L ([-+\d.]+)%")


def et_min(h, m):
    return (int(h) - 4) * 60 + int(m) - 570      # EDT; minute 0 = 9:30


def bot_trades(day):
    T = []
    for l in open(OUT / f"entry1002_live_{day}.out"):
        g = LINE.match(l)
        if g:
            T.append({"sym": g.group(3), "buy_m": et_min(g.group(1), g.group(2)), "sell_m": et_min(g.group(4), g.group(5)),
                      "pl": float(g.group(6)) - 0.1})
    return T


def slots(T):
    open_, kept = [], []
    for t in sorted(T, key=lambda t: t["buy_m"]):
        open_ = [s for s in open_ if s > t["buy_m"]]
        if len(open_) < SLOTS:
            kept.append(t); open_.append(t["sell_m"])
    return kept


def main():
    days = sorted(p.name[15:25] for p in 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
    R = {"BOT": [], "A star times it": [], "B bot buys, star sells": []}
    for day in days:
        bt = bot_trades(day)
        first = {}
        for t in bt:
            first[t["sym"]] = min(first.get(t["sym"], 999), t["buy_m"])
        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)
        A, B = [], []
        for s, f in first.items():
            ref = REF.load(day, s)
            a = L2.day_arrays(get(s), ref, day, tuple(bench)) if ref else None
            if a is None:
                continue
            A += [{"sym": s, **t} for t in S3.run_day(lib, wmask, m3, nb, ns, day, a, can_buy=lambda m, f=f: m >= f)]
            B += [{"sym": s, **t} 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)]
        REF._CACHE.clear()
        for k, T in (("BOT", bt), ("A star times it", A), ("B bot buys, star sells", B)):
            all_ = [{"day": day, **t} for t in T]
            R[k].append((day, all_, [{"day": day, **t} for t in slots(T)]))
        print(day, {k: round(sum(t["pl"] for t in v[-1][2]) * SIZE / 100, 2) for k, v in R.items()}, flush=True)
    json.dump({k: [(d, a, s) for d, a, s in v] for k, v in R.items()}, open(HERE / f"star_takeover{'_allmarks' if '--allmarks' in sys.argv else ''}.json", "w"), default=float)
    half = days[len(days) // 2]
    print(f"\n{len(days)} days {days[0]}..{days[-1]}, ${SIZE:.0f} per trade, 0.1% cost")
    for k, v in R.items():
        for lab, idx in (("every signal", 1), (f"{SLOTS} slots", 2)):
            T = [t for d, a, s in v for t in (a if idx == 1 else s)]
            p = np.array([t["pl"] for t in T]) if T else np.zeros(1)
            h1 = sum(t["pl"] for t in T if t["day"] < half) * SIZE / 100; h2 = sum(t["pl"] for t in T if t["day"] >= half) * SIZE / 100
            byd = {}
            for t in T:
                byd[t["day"]] = byd.get(t["day"], 0) + t["pl"]
            print(f"{k:24} {lab:12}: {len(T):3} trades, win {(p > 0).mean():.0%}, avg {p.mean():+.2f}%, "
                  f"total ${p.sum() * SIZE / 100:+8.2f} (halves ${h1:+.0f} / ${h2:+.0f}), positive days {sum(x > 0 for x in byd.values())}/{len(days)}")


if __name__ == "__main__":
    main()
