#!/usr/bin/env python3
"""Recalculate NLQ relative delays from retained guest BASIC count arrays.

Uses only captured guest data and BASIC lines 2290-2510. Binary64 recalculation
can differ from BASIC's 32-bit mantissa in the last digits; displayed values
must match the guest. This supplies no physical propagation-delay oracle.
"""
import json
import math
from pathlib import Path


def basic_float(data):
    assert len(data) == 5
    if data[0] == 0:
        return 0.0
    fraction = ((data[1] & 127) << 24) | int.from_bytes(data[2:], 'big')
    return (-1 if data[1] & 128 else 1) * math.ldexp(1 + fraction / 2**31, data[0] - 129)


def recalculate(path):
    snapshot = json.loads(path.read_text())
    data = bytes.fromhex(snapshot['snapshotHex'])
    assert len(data) == snapshot['snapshotEnd'] - snapshot['VARTAB']
    array_start = snapshot['ARYTAB'] - snapshot['VARTAB']
    assert array_start % 7 == 0
    scalars = {}
    for offset in range(0, array_start, 7):
        name = data[offset:offset + 2]
        if all(value < 128 for value in name):
            scalars[name.decode('ascii').rstrip('\0')] = basic_float(data[offset + 2:offset + 7])
    assert scalars['AL'] == 10000
    assert abs(scalars['FQ'] - .98525) < 1e-9
    offset = array_start
    counts = None
    while offset < len(data):
        name = data[offset:offset + 2]
        length = int.from_bytes(data[offset + 2:offset + 4], 'little')
        dimensions = data[offset + 4]
        assert 0 < length <= len(data) - offset
        header = 5 + 2 * dimensions
        if name == b'R\0':
            # BASIC stores bounds in reverse order; the first subscript varies fastest.
            bounds = [int.from_bytes(data[offset + 5 + 2*i:offset + 7 + 2*i], 'big')
                      for i in range(dimensions)][::-1]
            assert bounds == [2, 2, 12]
            assert length - header == math.prod(bounds) * 5
            counts = [basic_float(data[i:i + 5]) for i in range(offset + header, offset + length, 5)]
        offset += length
    assert offset == len(data) and counts is not None
    assert all(value.is_integer() and 0 <= value <= scalars['AL'] for value in counts)
    columns = []
    for column, (drive_rising, c64_rising) in enumerate(((0, 0), (0, 1), (1, 0), (1, 1))):
        samples = [int(counts[drive_rising + 2*c64_rising + 4*delay]) for delay in range(2, 12)]
        values = []
        used_delays = []
        for delay, positive in zip(range(2, 12), samples):
            percentage = math.floor(100 * positive / scalars['AL'] + .5)
            if percentage not in (0, 100):
                cycles = delay - (100 * positive / scalars['AL'] / scalars['DV'])
                values.append(cycles / scalars['FQ'])
                used_delays.append(delay)
        assert values
        average = math.fsum(values) / len(values)
        displayed = math.floor(average * 100 + .5) / 100
        assert abs(displayed - scalars['X' + str(column + 1)]) < 1e-8
        minimum = (2.75, 2.72, 2.77, 2.74)[column]
        maximum = (3.00, 2.94, 3.01, 2.98)[column]
        columns.append(dict(c64Rising=bool(c64_rising), driveRising=bool(drive_rising),
            delays=list(range(2, 12)), positiveResponses=samples, usedDelays=used_delays,
            recalculatedMicroseconds=average, displayedMicroseconds=displayed,
            minimumMicroseconds=minimum, maximumMicroseconds=maximum,
            originalRangeOutcome='FAIL' if displayed < minimum or displayed > maximum else 'PASS'))
    return dict(model=snapshot['model'],trialsPerDelay=int(scalars['AL']),basicFrequencyMHz=scalars['FQ'],
                basicDivider=scalars['DV'],columns=columns)


if __name__ == '__main__':
    folder = Path(__file__).with_name('snapshots')
    print(json.dumps([recalculate(folder / (model + '.json')) for model in ('C64', 'C64C')], indent=2))
