import asyncio, json, subprocess, sys, requests, websockets

def key():
    return subprocess.check_output(["security","find-generic-password","-s","getxapi-key","-w"]).decode().strip()

def browser_ws(port=9555):
    v=requests.get(f"http://127.0.0.1:{port}/json/version").json()
    return v["webSocketDebuggerUrl"]

async def cookies():
    ws_url=browser_ws()
    async with websockets.connect(ws_url, max_size=50_000_000) as ws:
        await ws.send(json.dumps({"id":1,"method":"Storage.getCookies"}))
        while True:
            m=json.loads(await ws.recv())
            if m.get("id")==1:
                return m["result"]["cookies"]

def main():
    ck={c["name"]:c["value"] for c in asyncio.get_event_loop().run_until_complete(cookies())
        if c.get("domain","").endswith("x.com") and c["name"] in ("auth_token","ct0","twid")}
    print("cookies:", {k:(len(v)) for k,v in ck.items()})
    if "auth_token" not in ck:
        print("NO_AUTH_TOKEN"); sys.exit(1)
    K=key()
    H={"Authorization":f"Bearer {K}","Content-Type":"application/json"}
    base="https://api.getxapi.com/twitter/tweet"
    body={"auth_token":ck["auth_token"],"ct0":ck.get("ct0"),"twid":ck.get("twid")}
    # 1) create root
    r=requests.post(f"{base}/create",headers=H,json={**body,"text":"internal transport check, ignore (auto-delete)"} ,timeout=60)
    print("CREATE",r.status_code,r.text[:200])
    j=r.json(); rid=(j.get("data") or {}).get("id") or j.get("id")
    if not rid: print("NO_ROOT_ID"); sys.exit(1)
    # 2) reply to it
    r2=requests.post(f"{base}/create",headers=H,json={**body,"text":"reply check (auto-delete)","reply_to_tweet_id":rid},timeout=60)
    print("REPLY",r2.status_code,r2.text[:200])
    j2=r2.json(); cid=(j2.get("data") or {}).get("id") or j2.get("id")
    # 3) delete both
    for tid,label in [(cid,"reply"),(rid,"root")]:
        if tid:
            d=requests.post(f"{base}/delete",headers=H,json={**body,"tweet_id":tid},timeout=60)
            print("DELETE",label,d.status_code,d.text[:150])
main()
