"""Convert r6weth.db (v4 WETH pools, 21 Sep - 7 Oct) to v4tape format for replaying h100/h3k. Pool-view amounts (a=token0, q=token1)."""
import sqlite3, json, os, sys
OUT = "/root/tm/replay/tape/"; os.makedirs(OUT, exist_ok=True)
c = sqlite3.connect("file:/opt/ppcopy/r6weth.db?mode=ro", uri=True)
Z = "0x" + "0" * 40; pools = {}
with open(OUT + "pools.jsonl", "w") as f:
    for pid, tok, q, t0, fee, hk, blk, ct in c.execute("select pool,token,quote,token0,fee,hooks,created_block,created_t from meta where venue='v4'"):
        cls = "H3000" if fee == 3000 and hk and hk != Z else "A1" if fee == 100 else "other"
        if cls == "other": continue
        pools[pid] = 1
        f.write(json.dumps(dict(pool_id=pid, cls=cls, token=tok, quote="weth", hooks=hk or Z, fee=fee, block=blk, init_time=ct, emitted_t=ct)) + "\n")
n = 0; tmax = 0
with open(OUT + "swaps.jsonl", "w") as f:
    for pid, blk, t, li, a, q, px, liq in c.execute("select pool,block,t,li,a,q,px,liq from ev where venue='v4' and kind=1 order by pool,block,li"):
        if pid not in pools: continue
        f.write(json.dumps(dict(pool_id=pid, block=blk, t=int(t), log_index=li, amount0=int(a), amount1=int(q), sqrtP=int(px or 0), liq=int(liq or 0), emitted_t=t)) + "\n"); n += 1; tmax = max(tmax, t)
json.dump({"n_pools": len(pools), "n_swaps": n, "tape_end": tmax}, open(OUT + "meta.json", "w")); print(len(pools), n, tmax)
