import sys,statistics as S,time,sqlite3
sys.argv=['x','/tmp/_o.md']
src=open('/opt/crew/work/research/capture/capture.py').read().split("rows = []")[0]
exec(src)
rows=[]
for pool,tok,tb,mult,ex,pk,cap in tr:
    p=path(pool,tb)
    if not p: continue
    rows.append(dict(tb=tb,mult=mult,ex=ex,p=p,cap=cap,peak=max(x for _,x in p),mn=min(x for _,x in p),last=p[-1][1]))
HO=time.mktime(time.strptime("2026-10-12","%Y-%m-%d"))-time.timezone
def rug(r):
    if r['mult']<0.05: return True
    p=[(t,x) for t,x in r['p'] if t<=TS]
    return any(b<0.1*a for (_,a),(_,b) in zip(p,p[1:]))
def sim2(r,kw,rugcost=True):
    if rugcost and rug(r): return 0.0   # rugged: nothing sellable, any rule
    return sim(r['p'],**kw)
def delayed(p,delay,stop):  # no stop for first delay s, then stop
    pk=1;last=1
    for t,x in p:
        if t>TS: return last
        last=x
        if t>=delay and x<=stop: return stop
    return last
R={"base stop0.5":dict(),"stop0.3":dict(stop=.3),"stop0.2":dict(stop=.2),"no stop 4h":dict(stop=0.0),
   "no stop 4h, 8h":dict(stop=0.0,ts=28800),"stop0.5 + trail0.5 from 5x":dict(trail=.5,arm=5)}
def rep(sub,label):
    out=[f"**{label}** n={len(sub)} rugs={sum(rug(r) for r in sub)} live mean={S.mean(r['mult'] for r in sub):.2f}"]
    for n,kw in R.items():
        for rc in (False,True):
            v=sorted((sim2(r,kw,rc) for r in sub),reverse=True)
            out.append(f"| {n} | rug-cost={rc} | mean {S.mean(v):.2f} | w/o top3 {S.mean(v[3:]):.2f} | median {S.median(v):.2f} |")
    for d in (300,900,1800):
        for st in (.5,.3):
            v=sorted((0.0 if rug(r) else delayed(r['p'],d,st) for r in sub),reverse=True)
            out.append(f"| delay{d}s then stop{st} | rug-cost=True | mean {S.mean(v):.2f} | w/o top3 {S.mean(v[3:]):.2f} | median {S.median(v):.2f} |")
    return "\n".join(out)
tr_=[r for r in rows if r['tb']<HO]; ho=[r for r in rows if r['tb']>=HO]
print(rep(rows,"ALL"));print();print(rep(tr_,"TRAIN <12 Oct"));print();print(rep(ho,"HOLDOUT 12-14 Oct"))
