#!/usr/bin/env python3
"""Rerun the published address and package examples. No key or account required."""
import argparse
import hashlib
import json
import urllib.request
from pathlib import Path


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--out', default='public-reproduction.json')
    args = parser.parse_args()
    destination = Path(args.out)
    if destination.exists():
        raise SystemExit('Choose a new --out; existing evidence will not be overwritten.')
    pack = Path(__file__).resolve().parent
    request = urllib.request.Request(
        'https://prophit.ai/api/public-evaluation/five-hard-transactions/v1/reproduce',
        headers={'User-Agent': 'Prophit-FiveHardTransactions-Reference/1.0'})
    with urllib.request.urlopen(request, timeout=45) as response:
        actual = json.load(response)
    destination.write_text(json.dumps(actual, indent=2) + '\n', encoding='utf-8')
    expected = json.loads((pack / 'address-executions.json').read_text())
    manifest = json.loads((pack / 'manifest.json').read_text())
    assert actual['pack_version'] == manifest['version'], 'Version differs'
    assert actual['source_hashes'] == manifest['source_hashes'], 'Source version differs'
    for reference, fresh in zip(expected['results'], actual['address_results'], strict=True):
        assert reference['input'] == fresh['input'], 'Address inputs differ'
        for key in ('high', 'loc_code'):
            assert reference['result'][key] == fresh['result'][key], f'Address {key} differs'
    content = (pack / 'SYNTHETIC-DO-NOT-FILE-ST1.txt').read_bytes()
    assert actual['st1']['content'].encode('ascii') == content, 'Package bytes differ'
    assert actual['st1']['sha256'] == hashlib.sha256(content).hexdigest()
    assert actual['st1']['validation']['result'] == 'conforming'
    print(f"MATCH: fresh address/package execution at {actual['executed_at']}. Saved to {destination}.")
    print('This is component reproduction with synthetic/reference inputs, not a filing or full-engine certification.')


if __name__ == '__main__':
    main()
