"""Retrieve public aggregates only, then verify the mean and table arithmetic.

The fixed event-time window is not a frozen database snapshot. A later query may
include late arrivals. No transaction lists, wallets or private APIs are queried.
"""
import argparse
import datetime
import decimal
import json
import pathlib
import urllib.request

URL = 'https://inferenceview.com/api/metrics?since=1789171200&until=1789257600'


def verify(envelope):
    d = envelope.get('data', envelope.get('metrics'))
    decimal.getcontext().prec = 100
    D = decimal.Decimal
    assert d['total'] == d['analyzed']
    assert d['truncated'] is False
    assert 0 <= d['priced_transactions'] <= d['total']
    assert D(d['nominal']) / D(d['priced_transactions']) == D(d['average_nominal'])
    assert sum(row['count'] for row in d['histogram']) == d['total']
    assert d['coverage']['window_since'] == 1789171200
    assert d['coverage']['window_until'] == 1789257600
    return {'retrieved_at': envelope['retrieved_at'], 'total': d['total'],
            'known_value_records': d['priced_transactions'],
            'unknown_value_records': d['total'] - d['priced_transactions'],
            'mean': d['average_nominal'], 'median': d['median_nominal'],
            'checks': 'mean, histogram, denominator and fixed-window arithmetic passed'}


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--read', type=pathlib.Path, help='Verify an existing evidence JSON without network access')
    parser.add_argument('--output', type=pathlib.Path, default=pathlib.Path('fresh-aggregate.json'))
    args = parser.parse_args()
    if args.read:
        envelope = json.loads(args.read.read_text())
    else:
        req = urllib.request.Request(URL, headers={'Accept': 'application/json', 'User-Agent': 'InferenceView-research/1.0'})
        with urllib.request.urlopen(req, timeout=45) as response:
            data = json.load(response)
        envelope = {'retrieved_at': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'url': URL, 'data': data}
        args.output.write_text(json.dumps(envelope, indent=2) + '\n')
    print(json.dumps(verify(envelope), indent=2))
