import asyncio, json, time
import websockets
WS="wss://ourworldoftext.com/ws/"
gy=8; x0=-32; W=52
def cell_of(x,y):
    tx,ty=x//16,y//8; return tx,ty,x-tx*16,y-ty*8
async def fetch(ws):
    txs=sorted({cell_of(x,gy)[0] for x in range(x0,x0+W)})
    await ws.send(json.dumps({"kind":"fetch","fetchRectangles":[{"minX":min(txs),"minY":1,"maxX":max(txs),"maxY":1}]}))
    tiles={}; t0=time.monotonic()
    while time.monotonic()-t0<6:
        d=json.loads(await asyncio.wait_for(ws.recv(),timeout=5))
        if d.get("kind")=="fetch":
            for k,v in d["tiles"].items():
                ty,tx=map(int,k.split(",")); tiles[(tx,ty)]=v
            if all((tx,1) in tiles for tx in txs): break
    row=[]
    for x in range(x0,x0+W):
        tx,ty,cx,cy=cell_of(x,gy); v=tiles.get((tx,1))
        row.append((v.get("content"," "*128)[cy*16+cx]) if v else " ")
    return "".join(row)
async def main():
    async with websockets.connect(WS,origin="https://ourworldoftext.com",
            additional_headers={"User-Agent":"Mozilla/5.0 Chrome/120"},max_size=None,open_timeout=20) as ws:
        before=await fetch(ws)
        print("BEFORE:",repr(before))
        edits=[]; ts=int(time.time()*1000); seq=1
        for x in range(x0,x0+W):
            tx,ty,cx,cy=cell_of(x,gy); edits.append([ty,tx,cy,cx,ts," ",seq,0,-1]); seq+=1
        await ws.send(json.dumps({"kind":"write","edits":edits}))
        await asyncio.sleep(3)
        after=await fetch(ws)
        print("AFTER :",repr(after))
        print("CLEAN =", after.strip()=="")
asyncio.run(main())
