"""Run python3 wallet-reconciliation-check.py beside the downloaded JSON file."""
import json
from decimal import Decimal
from pathlib import Path

sample = json.loads(Path(__file__).with_name("wallet-reconciliation.json").read_text(), parse_float=Decimal)
trades = sample["trades"]["data"]
activities = sample["activity"]["data"]
assert all(sample[key]["pagination"]["has_more"] is False for key in ("trades", "activity", "open", "closed"))
assert len(trades) == len(activities) == len(sample["receipts"]) == 2
shares = notional = reported = Decimal(0)
for trade in trades:
    tx = trade["transaction_hash"]
    activity, = [row for row in activities if row["transaction_hash"] == tx]
    receipt, = [row for row in sample["receipts"] if row["transactionHash"] == tx]
    for key in ("proxy_wallet", "condition_id", "token_id", "timestamp", "side", "size", "price"):
        assert activity[key] == trade[key]
    assert sample["start"] <= trade["timestamp"] <= sample["end"]
    assert trade["proxy_wallet"] == sample["wallet"] and trade["condition_id"] == sample["condition"]
    assert trade["side"] == "BUY" and activity["type"] == "TRADE" and receipt["status"] == "0x1"
    event = receipt["transferSingle"]
    assert event["topics"][0] == "0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62"
    assert event["topics"][3][-40:] == sample["wallet"][2:]
    assert int(event["data"][2:66], 16) == int(trade["token_id"])
    assert int(event["data"][66:], 16) == trade["size"] * 10**6
    shares += trade["size"]
    notional += trade["size"] * trade["price"]
    reported += activity["usdc_size"]
print("Shares:", shares, "fill notional:", notional, "activity USDC:", reported, "difference:", reported-notional)
print("Later condition snapshot: open", len(sample["open"]["data"]), "closed", len(sample["closed"]["data"]))
