"""Offline Decimal parser for an explicitly scoped Polymarket v2 OI snapshot.
No network, credentials, wallet operations or orders. No file runs self-checks.
Usage: python3 polymarket-open-interest.py snapshot.json [--global]
"""
import argparse
import json
import re
from decimal import Decimal as D
from pathlib import Path


def reject_constant(value):
    raise ValueError("Nonfinite JSON constant: " + value)


def read_snapshot(text, global_scope=False, expected_conditions=None):
    payload = json.loads(text, parse_float=D, parse_int=D, parse_constant=reject_constant)
    if not isinstance(payload, dict) or not isinstance(payload.get("data"), list):
        raise ValueError("Expected v2 object with a data list")
    rows = payload["data"]
    if not rows:
        raise ValueError("No observations returned; this is not a zero balance")
    values = {}
    for row in rows:
        if not isinstance(row, dict) or "condition_id" not in row or "value" not in row:
            raise ValueError("Missing row fields")
        condition = row["condition_id"]
        is_global = condition is None or condition == "GLOBAL"
        if global_scope != is_global:
            raise ValueError("Do not mix global and market scopes")
        if not is_global and (not isinstance(condition, str) or not re.fullmatch(r"0x[0-9a-fA-F]{64}", condition)):
            raise ValueError("Unexpected condition identifier")
        key = "GLOBAL" if is_global else condition.lower()
        if key in values:
            raise ValueError("Duplicate condition/global row; do not add it twice")
        raw = row["value"]
        if isinstance(raw, bool) or not isinstance(raw, (D, str)):
            raise ValueError("Expected a decimal number or decimal string")
        value = D(raw)
        if not value.is_finite() or value < 0:
            raise ValueError("Expected finite nonnegative value")
        values[key] = value
    if expected_conditions is not None:
        if global_scope or set(values) != {x.lower() for x in expected_conditions}:
            raise ValueError("Returned condition set does not match the requested set")
    return values


def self_check():
    a, b = "0x" + "a"*64, "0x" + "b"*64
    fixture = '{"data":[{"condition_id":"'+a+'","value":120.10},{"condition_id":"'+b+'","value":"80.20"}]}'
    values = read_snapshot(fixture, expected_conditions={a, b})
    assert sum(values.values()) == D("200.30")
    assert values[a] == D("120.10")
    for marker in [None, "GLOBAL"]:
        assert read_snapshot(json.dumps({"data":[{"condition_id":marker,"value":"200.30"}]}), True) == {"GLOBAL":D("200.30")}
    bad = ['[]', '{"data":[]}', '{"data":[{"condition_id":null,"value":1}]}',
           '{"data":[{"condition_id":"UNKNOWN","value":1}]}',
           '{"data":[{"condition_id":"'+a+'","value":-1}]}',
           '{"data":[{"condition_id":"'+a+'","value":true}]}',
           '{"data":[{"condition_id":"'+a+'","value":"NaN"}]}',
           '{"data":[{"condition_id":"'+a+'","value":1},{"condition_id":"'+a+'","value":1}]}']
    for text in bad:
        try:
            read_snapshot(text)
        except ValueError:
            pass
        else:
            raise AssertionError("Expected invalid fixture rejection")
    try:
        read_snapshot(fixture, expected_conditions={a})
    except ValueError:
        pass
    else:
        raise AssertionError("Expected scope-set mismatch")
    print("Fictional market subtotal: 200.30; Decimal, scope, duplicate and missing-data checks passed.")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("snapshot", nargs="?")
    parser.add_argument("--global", dest="global_scope", action="store_true")
    args = parser.parse_args()
    if args.snapshot:
        result = read_snapshot(Path(args.snapshot).read_text(), args.global_scope)
        for condition, value in result.items():
            print(condition, str(value))
        print("Scope:", "global" if args.global_scope else "selected conditions only")
        print("Source units: analytics documentation labels OI values in USDC; valuation not independently reconstructed.")
    else:
        self_check()
