#!/usr/bin/env python3
"""Replay a logged fork RPC session against a fresh anvil fork and diff results."""
import json, sys, time, urllib.request
F = sys.argv[2] if len(sys.argv) > 2 else "http://127.0.0.1:8547"
def same(a, b):
    """Equal, allowing words that differ by < 600 (fork timestamps drift between runs)."""
    if a == b: return True
    if not (a and b) or len(a) != len(b): return False
    w = lambda x: [int(x[2 + i:66 + i], 16) for i in range(0, len(x) - 2, 64)]
    return all(abs(p - q) < 600 for p, q in zip(w(a), w(b)))
log = json.load(open(sys.argv[1])); hashes = {}; diffs = 0
def call(b):
    r = urllib.request.Request(F, json.dumps(b).encode(), {"Content-Type": "application/json"})
    return json.load(urllib.request.urlopen(r, timeout=120))
for e in log:
    req = json.loads(json.dumps(e["req"]))
    if req["method"] == "eth_getTransactionReceipt":
        req["params"] = [hashes.get(req["params"][0], req["params"][0])]
    if req["method"] == "eth_getTransactionReceipt":
        for _ in range(100):
            got = call(req)
            if got.get("result") or not e["resp"].get("result"): break
            time.sleep(0.2)
    else:
        got = call(req)
    if req["method"] == "eth_sendTransaction" and "result" in got and "result" in e["resp"]:
        hashes[e["resp"]["result"]] = got["result"]; continue
    if req["method"] == "eth_getTransactionReceipt":
        a, b = (e["resp"].get("result") or {}).get("status"), (got.get("result") or {}).get("status")
        if a and a != b: diffs += 1; print("STATUS DIFF", a, b)
        continue
    if req["method"] == "eth_call" and not same(e["resp"].get("result"), got.get("result")):
        diffs += 1; print("CALL DIFF", req["params"][0].get("data", "")[:10], e["resp"].get("result"), got.get("result"))
print("diffs:", diffs)
