"""
group_compare.py -- [2026-10-09] The user: compare the GROUP BUY SIGNALS (log only, trade/group_watch.py) with the
bot's real entries -- was the signal the right place to buy?
For each signal: what happened after the signal price (+3% before -1.5% = WIN, etc., max gain, to the close, at the
real 0.2% cost), the day's right entry for that stock (the user's deep-V rule, analyze_trades.deep_v_entry), and
whether a bot bought the same stock (time, price, real P/L). For each bot entry without a signal: the stock's group
at the last checkpoint before the buy.
Appends to data/group_watch/compare.jsonl.      python3 group_compare.py [DAY ...]   (default today)
cron: 16:25 weekdays (after reconcile_fills 16:03)
"""
import json
import sys
from datetime import date, datetime
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import analyze_trades as A  # noqa: E402

TRADE = Path("/var/www/screener/trade")
SRC = {"trade_bot": TRADE, "star_bot": Path("/var/www/screener/premarket")}
OUT = TRADE / "data" / "group_watch" / "compare.jsonl"
COST, WIN, STOP = 0.2, 3.0, 1.5
hm = lambda t: t.strftime("%H:%M")


def after(B, i, P):
    up, dn = P * (1 + WIN / 100), P * (1 - STOP / 100)
    res, pl = "FLAT", (B[-1]["c"] / P - 1) * 100
    for b in B[i:]:
        if b["m"] > 385:
            break
        if b["l"] <= dn:
            res, pl = "LOSS", -STOP; break
        if b["h"] >= up:
            res, pl = "WIN", WIN; break
    rest = [b for b in B[i:] if b["m"] <= 385]
    mx = max(b["h"] for b in rest) if rest else P
    close = [b for b in B if b["m"] <= 385][-1]["c"]
    return res, round(pl - COST, 3), round((mx / P - 1) * 100, 2), round((close / P - 1) * 100 - COST, 3)


def run(day, c):
    p = TRADE / "data" / "group_watch" / f"{day}.jsonl"
    rows = [json.loads(l) for l in open(p)] if p.exists() else []
    if not rows:
        print(day, "no group rows"); return
    sig = {r["sym"]: r for r in rows if r.get("signal") == "BUY"}
    trades = []
    for src, root in SRC.items():
        f = root / "data" / "trades" / f"{day}_trades.jsonl"
        for l in (open(f) if f.exists() else []):
            t = json.loads(l)
            if t.get("entry_time") and t.get("exit_price"):
                t["source"] = src; trades.append(t)
    bars = {}
    get = lambda s: bars.setdefault(s, A.load_bars(c, s, day, None))
    out = []
    print(f"\n{day}: {len({r['sym'] for r in rows})} stocks grouped, {len(sig)} GROUP BUY SIGNALS, {len(trades)} bot trades")
    for s, r in sorted(sig.items(), key=lambda x: x[1]["t"]):
        B = get(s)
        i = next((k for k, b in enumerate(B) if b["m"] >= r["t"]), None)
        if i is None:
            continue
        res, pl, mx, tc = after(B, i, r["price"])
        dv = A.deep_v_entry(B, None)
        right = {"buy_t": hm(B[dv[1]]["t"]), "buy": B[dv[1]]["c"], "sell_t": hm(B[dv[2]]["t"]), "gain": round(dv[3] * 100, 2)} if dv else None
        bot = [t for t in trades if t["symbol"] == s]
        o = {"day": day, "kind": "signal", "sym": s, "sig_t": r["check"], "sig_price": r["price"], "group": r["group"],
             "style": r["style"], "res": res, "pl": pl, "max_after": mx, "to_close": tc, "right": right,
             "bot": [{"source": t["source"], "buy_t": hm(datetime.fromisoformat(t["entry_time"]).astimezone(A.ET)),
                      "buy": t["entry_price"], "pl": t.get("pl_dollars")} for t in bot]}
        out.append(o)
        print(f"  SIGNAL {s:5} {r['check']} @ {r['price']:.2f} {r['group']} [{r['style']}] -> {res} {pl:+.2f}% "
              f"(max {mx:+.2f}%, to close {tc:+.2f}%)"
              + (f" | right entry {right['buy_t']} {right['buy']:.2f} ({right['gain']:+.2f}%)" if right else " | no deep V")
              + "".join(f" | {b['source']} bought {b['buy_t']} {b['buy']:.2f} ${b['pl']:+.2f}" for b in o["bot"]))
    for t in trades:
        s = t["symbol"]
        et = datetime.fromisoformat(t["entry_time"]).astimezone(A.ET)
        m = (et.hour - 9) * 60 + et.minute - 30
        prior = [r for r in rows if r["sym"] == s and r["t"] <= m]
        g = prior[-1] if prior else None
        o = {"day": day, "kind": "bot_entry", "source": t["source"], "sym": s, "buy_t": hm(et), "buy": t["entry_price"],
             "pl": t.get("pl_dollars"), "group_before": g["group"] if g else None, "label_before": g["label"] if g else None,
             "signal": (sig[s]["check"] if s in sig else None)}
        out.append(o)
        print(f"  BOT    {s:5} {t['source']:9} {hm(et)} @ {t['entry_price']:.2f} ${t.get('pl_dollars') or 0:+.2f} | group before: "
              + (f"{g['group']} {g['label']} at {g['check']}" if g else "not grouped")
              + (f" | signal {sig[s]['check']} @ {sig[s]['price']:.2f}" if s in sig else " | no signal"))
    old = [l for l in open(OUT)] if OUT.exists() else []
    old = [l for l in old if json.loads(l)["day"] != day]
    with open(OUT, "w") as fh:
        fh.writelines(old)
        for o in out:
            fh.write(json.dumps(o, default=str) + "\n")
    S = [o for o in out if o["kind"] == "signal"]
    if S:
        print(f"  signals: {len(S)}, WIN {sum(o['res'] == 'WIN' for o in S)} LOSS {sum(o['res'] == 'LOSS' for o in S)}, "
              f"avg {sum(o['pl'] for o in S) / len(S):+.3f}%/trade (+3/-1.5, 0.2% cost)")


if __name__ == "__main__":
    c = A.get_client()
    for d in (sys.argv[1:] or [date.today().isoformat()]):
        run(d, c)
