#!/usr/bin/env python3
import json
from pathlib import Path

cfg = json.loads((Path(__file__).parent / 'starter.json').read_text())
source = list(cfg['inputs'])
expected = [x * cfg['transform']['multiply'] + cfg['transform']['add'] for x in source]
pending, observed, stability_checks, cycles = None, [], 0, 0
while (source or pending is not None) and cycles < 100:
    ready = bool(cfg['sink_ready'][cycles]) if cycles < len(cfg['sink_ready']) else True
    before = pending
    if pending is not None and ready:
        observed.append(pending)
        pending = None
    if pending is None and source:
        pending = source.pop(0) * cfg['transform']['multiply'] + cfg['transform']['add']
    if before is not None and not ready:
        assert pending == before
        stability_checks += 1
    cycles += 1
assert observed == expected, (observed, expected)
print(f'PASS elastic-pipeline cycles={cycles} tokens={len(observed)} stall_stability={stability_checks}')
