"""star_lock_replay.py FROM TO -- [2026-10-27] replay the REAL Star trades between FROM and TO (premarket logs) through the LIVE profit-lock
code (premarket/monitor.py SessionOrchestrator._profit_lock + config star.profit_lock), minute by minute on Alpaca 1-min bars, from the
buy until Star's actual sell. If the raised stop is hit first -> sold there (at the stop or the bar open if it gapped); else unchanged."""
import sys, json, types, importlib.util
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
sys.path.insert(0, "/var/www/screener/premarket")
spec = importlib.util.spec_from_file_location("star_monitor", "/var/www/screener/premarket/monitor.py"); M = importlib.util.module_from_spec(spec); spec.loader.exec_module(M)
M.log.handlers.clear(); M.log.propagate = False
sys.path.insert(0, "/var/www/screener/trade/reports/ev3"); import star_stop_test as S
ET = ZoneInfo("America/New_York"); cfg = json.load(open("/var/www/screener/premarket/config.json"))["star"]
a, b = sys.argv[1], sys.argv[2]
T = [t for t in S.trades() if a <= t["day"] <= b]; byday = {}
for t in T:
    Bd = S.bars(t["day"], t["sym"]); y, mo, d = map(int, t["day"].split("-")); t0 = datetime(y, mo, d, 9, 30, tzinfo=ET)
    bars = [{"t": t0 + timedelta(minutes=m), "o": v[0], "h": v[1], "l": v[2], "c": v[3]} for m, v in sorted(Bd.items())]
    bm, em = S.toM(t["bt"]), S.toM(t["st"])
    pos = {"entry_price": t["buy"], "stop_price": t["stop"], "entry_time": datetime(y, mo, d, int(t["bt"][:2]), int(t["bt"][3:]), 30, tzinfo=ET).isoformat()}
    stub = types.SimpleNamespace(star_cfg=cfg, position_mgr=types.SimpleNamespace(_save=lambda: None))
    new = None; arm = None; best = t["buy"]
    for i, x in enumerate(bars):
        m = (x["t"].hour - 9) * 60 + x["t"].minute - 30
        if m <= bm or m >= em: continue
        M.SessionOrchestrator._profit_lock(stub, t["sym"], bars[:i + 1], pos)
        if pos.get("profit_lock") and arm is None: arm = x["t"].strftime("%H:%M")
        if pos.get("profit_lock") and x["l"] <= pos["stop_price"]:
            new = (x["t"].strftime("%H:%M"), min(pos["stop_price"], x["o"])); break
        best = max(best, x["h"])
    act = (t["sell"] - t["buy"]) * t["n"]; nb = (new[1] - t["buy"]) * t["n"] if new else act
    t.update(act=act, nb=nb, arm=arm, new=new, best=(best / t["buy"] - 1) * 100); byday.setdefault(t["day"], []).append(t)
print(f"Star trades {a} .. {b}: {len(T)} (live profit-lock code: arm +{cfg['profit_lock']['arm_pct']}%, keep {cfg['profit_lock']['keep']} of the best gain)\n")
print(f"{'day':10} | trades | armed | sold by lock | actual $ | with lock $ | diff $")
for d, L in byday.items():
    print(f"{d} | {len(L):6} | {sum(bool(t['arm']) for t in L):5} | {sum(bool(t['new']) for t in L):12} | {sum(t['act'] for t in L):+8.2f} | {sum(t['nb'] for t in L):+11.2f} | {sum(t['nb'] - t['act'] for t in L):+7.2f}")
A = sum(t["act"] for t in T); Bn = sum(t["nb"] for t in T)
print(f"{'TOTAL':10} | {len(T):6} | {sum(bool(t['arm']) for t in T):5} | {sum(bool(t['new']) for t in T):12} | {A:+8.2f} | {Bn:+11.2f} | {Bn - A:+7.2f}")
print("\nevery trade the lock CHANGED:")
for t in T:
    if t["new"]:
        print(f"  {t['day']} {t['sym']:5} buy {t['bt']} {t['buy']:.2f} | actual {t['st']} {t['sell']:.2f} ({(t['sell'] / t['buy'] - 1) * 100:+.2f}%, {t['why'][:38]}) "
              f"| lock armed {t['arm']}, sold {t['new'][0]} {t['new'][1]:.2f} ({(t['new'][1] / t['buy'] - 1) * 100:+.2f}%) | {t['nb'] - t['act']:+.2f} $")
print("\nlock armed but Star sold first (no change):", ", ".join(f"{t['day'][5:]} {t['sym']}" for t in T if t["arm"] and not t["new"]))
