"""v3cheap.py (A1.23): cheap-end cells under the mc5 base. Dust-guarded, 4 h time stop, stop 0.5x, pull = 0, real depth,
honest fill = signal at checkpoint, fill at the pool state 6 s later (end of next block). One position per token, base wins.
Cells: +5m $100k-250k, +5m $150k-250k, +3m $100k-250k. Pick on H1, test once on H2.
Add rule: base+cell H2 $/day > base H2 AND base+cell worst3 not worse AND cell stays positive without its top 2 coins."""
import collections, statistics as st, datetime, numpy as np
exec(open("/root/fwa1/v3exit.py").read().split("extdone = ")[0])
extdone = {r[0] for r in E.execute("SELECT DISTINCT pool FROM done")}
H = 3600; NEED = int((420 + 4 * H + 600) / SPB); FD = 6
allp = [p for p in pools if meta[p["pool"]][4] + NEED <= head]
for p in allp: CACHE[p["pool"]] = path12(p)
def series_h(p, usd, ts):
    pth, pull, pf, sup = CACHE[p["pool"]]
    i0 = state(pth, ts)
    if i0 is None or pth[i0][4] < 0.1 or not any(x[2] for x in pth[:i0 + 1]): return None
    L0 = Lat(pth, i0)
    if not L0: return None
    mc = pth[i0][1] ** 2 * sup * p["eu"]
    i = state(pth, ts + FD); L = Lat(pth, i)
    if not L: return None
    eu = p["eu"]; gas = 0.05 / eu; x = usd / eu
    q = buy(pth[i][1], L, x * (1 - pf) * 0.99 - gas)
    T = []; M = []
    for k in range(i + 1, len(pth)):
        if pth[k][0] <= ts + FD: continue
        Lk = Lat(pth, k)
        if not Lk or pth[k][3] < 0.01: continue
        out = min(sell(pth[k][1], Lk, q), 0.9 * (pth[k][4] + x))
        T.append(pth[k][0]); M.append(max(0, out * (1 - pf) * 0.99 - gas) / x)
    return np.array(T), np.array(M), pull, (sell(pth[i][1], L, q) * (1 - pf) * 0.99 - gas) / x, mc
def ex(s, te, stop=0.5):
    T, M, pull, m0, mc = s
    ok = T <= te + 4 * H; Tn, Mn = T[ok], M[ok]
    for k in range(len(Mn)):
        if pull is not None and pull <= Tn[k]: return 0.0
        if Mn[k] <= stop:
            j = max(k, int(np.searchsorted(T, Tn[k] + 3, "right")) - 1); return float(M[j])
    if pull is not None and pull <= te + 4 * H: return 0.0
    return float(Mn[-1]) if len(Mn) else m0
def book(ts, lo, hi, usd):
    R = []
    for p in allp:
        s = series_h(p, usd, ts)
        if s and lo <= s[4] < hi: R.append((p, ex(s, ts + FD)))
    return R
alld = sorted({day(p["t"]) for p in allp}); D1 = [d for d in alld if d < day(CUT)]; D2 = [d for d in alld if d >= day(CUT)]
def worst3(R, days):
    pn = collections.defaultdict(float)
    for p, x, u in R: pn[day(p["t"])] += (x - 1) * u
    dl = sorted(datetime.date(2026, int(d[:2]), int(d[3:])) for d in days)
    cal = [dl[0] + datetime.timedelta(j) for j in range((dl[-1] - dl[0]).days + 1)]
    v = [pn.get(c.strftime("%m-%d"), 0.0) for c in cal]
    return min(sum(v[i:i + 3]) for i in range(max(1, len(v) - 2)))
def S(R, days):
    R = [r for r in R if day(r[0]["t"]) in days]; v = [x for p, x, u in R]
    if not v: return dict(n=0, usd=0, w3=0, top2=0, tpd=0)
    pnl = sorted(((x - 1) * u for p, x, u in R), reverse=True)
    return dict(n=len(v), tpd=len(v) / len(days), mean=st.mean(v), med=st.median(v), usd=sum(pnl) / len(days), w3=worst3(R, days),
                top2=sum(pnl[2:]), win=sum(x > 1 for x in v) / len(v))
def fmt(d): return ("n%d (%.1f/day) mean %.2fx med %.2fx $%.0f/day worst3 $%.0f without top2 $%.0f" % (d["n"], d["tpd"], d["mean"], d["med"], d["usd"], d["w3"], d["top2"])) if d["n"] else "n0"
print("pools %d (with 2h-12h ext %d)  days H1 %d H2 %d" % (len(allp), sum(p["pool"] in extdone for p in allp), len(D1), len(D2)), flush=True)
for usd in (100, 1000):
    base = [(p, x, usd) for p, x in book(300, 2.5e5, 1e6, usd)]; btok = {p["pool"] for p, x, u in base}
    b1, b2 = S(base, D1), S(base, D2)
    print("\n== $%d a trade ==\nBASE +5m $250k-1M | H1 %s | H2 %s" % (usd, fmt(b1), fmt(b2)), flush=True)
    for lab, ts, lo, hi in (("+5m $100k-250k", 300, 1e5, 2.5e5), ("+5m $150k-250k", 300, 1.5e5, 2.5e5), ("+3m $100k-250k", 180, 1e5, 2.5e5)):
        cell = [(p, x, usd) for p, x in book(ts, lo, hi, usd) if p["pool"] not in btok]
        noext = sum(p["pool"] not in extdone for p, x, u in cell)
        c1, c2 = S(cell, D1), S(cell, D2); m1, m2 = S(base + cell, D1), S(base + cell, D2)
        ok = m2["usd"] > b2["usd"] and m2["w3"] >= b2["w3"] and c2["top2"] > 0
        print("%s (no 2h+ data: %d)\n  cell H1 %s\n  cell H2 %s\n  base+cell H1 %s\n  base+cell H2 %s\n  H1 adds $%.0f/day -> %s on H2: %s" % (
            lab, noext, fmt(c1), fmt(c2), fmt(m1), fmt(m2), m1["usd"] - b1["usd"], "tested", "PASS" if ok else "FAIL"), flush=True)
