#!/usr/bin/env python3
"""Run fixed Python -> native Node.js -> Python JSON round trips, offline.

Requires the companion json-integer-roundtrip-node.mjs next to this file.
Requires node on PATH, with JSON.parse reviver context.source support.
Writes only its JSON report to stdout; does not change files or open a server.
"""
import hashlib
import json
from pathlib import Path
import platform
import subprocess


def compact(value):
    return json.dumps(value, ensure_ascii=False, separators=(',', ':'))


def main():
    # Explicit reference values, rather than JS number literals used as expectations.
    expectations = [
        ('0', '0'),
        ('42', '42'),
        ('9007199254740991', '9007199254740991'),
        ('9007199254740992', '9007199254740992'),
        ('9007199254740993', '9007199254740992'),
        ('9007199254740994', '9007199254740994'),
        ('9007199254740995', '9007199254740996'),
        ('-9007199254740993', '-9007199254740992'),
        ('9223372036854775807', '9223372036854775808'),
        ('-9223372036854775808', '-9223372036854775808'),
        ('18446744073709551615', '18446744073709551616'),
        ('1000000000000000000', '1000000000000000000'),
    ]
    fixtures = []
    for token, _ in expectations:
        original = int(token)
        numeric_wire = compact({'id': original})
        string_wire = compact({'id': str(original)})
        assert numeric_wire == '{"id":' + token + '}'
        assert json.loads(numeric_wire)['id'] == original
        fixtures.append({'numericWire': numeric_wire, 'stringWire': string_wire})
    node_script = Path(__file__).with_name('json-integer-roundtrip-node.mjs')
    run = subprocess.run(
        ['node', str(node_script)], input=compact(fixtures),
        text=True, stdout=subprocess.PIPE, check=True, timeout=30,
    )
    report = json.loads(run.stdout)
    assert len(report['cases']) == len(expectations)
    enriched = []
    for (token, represented), fixture, row in zip(expectations, fixtures, report['cases']):
        original = int(token)
        back = json.loads(row['numericOutput'])['id']
        assert row['input'] == fixture['numericWire']
        assert row['representedInteger'] == represented
        assert row['isInteger'] is True
        assert row['isSafeInteger'] == (abs(original) <= 2**53 - 1)
        assert row['stringValue'] == token
        assert row['stringOutput'] == fixture['stringWire']
        assert json.loads(row['stringOutput'])['id'] == token
        enriched.append({
            'originalInteger': token,
            'pythonParsedType': type(json.loads(row['input'])['id']).__name__,
            **row,
            'numericReturnInteger': str(back),
            'parsePreservedInteger': represented == token,
            'numericRoundTripPreserved': back == original,
            'stringRoundTripPreserved': True,
            'inputSha256': hashlib.sha256(row['input'].encode('utf-8')).hexdigest(),
        })
    report['cases'] = enriched
    assert report['cases'][8]['numberText'] == '9223372036854776000'
    assert report['cases'][8]['numericReturnInteger'] == '9223372036854776000'
    assert json.loads(report['reviver']['explicitBigIntOutput'])['id'] == expectations[8][0]
    exponent_value = json.loads(report['exponent']['input'])['id']
    assert type(exponent_value) is float
    assert int(exponent_value) == 9007199254740992
    report['exponent']['pythonParsedType'] = type(exponent_value).__name__
    report['exponent']['pythonRepresentedInteger'] = str(int(exponent_value))
    assert len(report['validation']) == 17
    assert sum(row['accepted'] for row in report['validation']) == 4
    report = {
        'experiment': 'Native JSON integer round trips; fixed synthetic fixtures',
        'runDate': '2026-10-30',
        'environment': {
            'python': platform.python_version(),
            'system': platform.system(),
            'macOS': platform.mac_ver()[0],
            'machine': platform.machine(),
            'node': report.pop('node'),
        },
        **report,
        'checks': {
            'numericCases': len(expectations),
            'numericParseChanged': sum(not row['parsePreservedInteger'] for row in enriched),
            'numericRoundTripChanged': sum(not row['numericRoundTripPreserved'] for row in enriched),
            'stringRoundTripsPreserved': len(enriched),
            'validationAccepted': 4,
            'validationRejected': 13,
            'allAssertionsPassed': True,
        },
        'limits': [
            'Fixed offline teaching fixtures; no HTTP, database, SDK or browser integration was tested.',
            'Node uses native JSON.parse/JSON.stringify and no patched BigInt.prototype.',
            'context.source conversion is tested for a plain integer token; exponent notation is rejected by BigInt.',
            'readId is a sample contract: canonical nonnegative decimal strings <= 9223372036854775807.',
            'Large integers in this report are strings to avoid damaging the evidence in another JSON reader.',
        ],
    }
    print(json.dumps(report, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()
