# fill age_s / cap_5m for radar backfill rows from v3live.db tape (radar.py definitions). Idempotent: rewrites sidecar.
import json,sqlite3,sys
out=sys.argv[1]
db=sqlite3.connect('file:/opt/sw/v3live.db?mode=ro',uri=True)
rows=[json.loads(l) for l in open('/opt/sw/radar/radar.jsonl')]
rows=[x for x in rows if x.get('backfill') and x['ev']=='cross']
seen=set(); n=0
with open(out+'.tmp','w') as f:
    for x in rows:
        k=(x['pool'],x['th'])
        if k in seen: continue
        seen.add(k)
        ft=db.execute('select min(t) from swaps where pool=?',(x['pool'],)).fetchone()[0]
        if ft is None: continue
        last=db.execute('select mcap_usd,t from swaps where pool=? and t<=? order by t desc,id desc limit 1',(x['pool'],ft+300)).fetchone()
        mx=db.execute('select max(t) from swaps where pool=?',(x['pool'],)).fetchone()[0]
        c5=round(last[0]) if last and mx>=ft+300 else None
        cr=db.execute('select created_t from pools where pool=?',(x['pool'],)).fetchone()
        f.write(json.dumps(dict(pool=x['pool'],token=x['token'],venue=x['venue'],th=x['th'],t=x['t'],age_s=x['t']-ft,
            created_t=cr[0] if cr else None,age_from_create_s=x['t']-cr[0] if cr and cr[0] else None,
            cap_first_radar=x['cap_first'],cap_first=(db.execute('select mcap_usd from swaps where pool=? order by t,id limit 1',(x['pool'],)).fetchone() or [None])[0],cap_5m=c5,cap_5m_known=c5 is not None))+'\n'); n+=1
import os; os.replace(out+'.tmp',out); print(n)
