import json
from pathlib import Path
p = Path(__file__).parent
read = lambda f: json.loads((p / f).read_text())
b,c = [read(f'initial-run-{lane}.json') for lane in 'BC']
assert len(b['cases']) == len(c['cases']) == 10
assert b['failure']['stage'] == 'ledger-final'  # Preserve original harness failure; no funds replay.
assert c['failure'] is None
for x,y in zip(b['cases'],c['cases']):
    assert (x['scenario'],x['method'],x['path'],x['code']) == (y['scenario'],y['method'],y['path'],y['code'])
    assert x['wire_shape'] == y['wire_shape']
assert b['payment_source']['gift'] == '0.01' and b['payment_source']['cash'] == '0.00'
assert c['payment_source']['cash'] == '0.01' and c['payment_source']['gift'] == '0.00'
for lane in 'BC':
    audit=read(f'independent-audit-{lane}.json')
    assert audit['all_financial_source_passed'] and all(audit['financial_source_checks'].values())
    assert audit['database_writes']==0 and audit['independent_new_connections']
    assert audit['net_retained']=={'cash':'0.01','gift':'0.00','store_pay_money':'0.01'}
    assert all(x['unchanged'] for x in audit['existing_source_sets'].values())
    red,green=[read(f'replay-{stage}-{lane}.json') for stage in ('red','green')]
    for r in (red,green):
        assert r['code']==0 and r['http_status']==200
        assert r['all_selected_business_sources_unchanged'] and r['temporary_auth_exact_deleted']
        assert r['business_funds_dml']==0 and r['source_before_sha256']==r['source_after_sha256']
    assert red['pay_time_length']==(19 if lane=='B' else 26)
    assert green['pay_time_length']==19 and green['pay_time_seconds_match_original_source']
    assert green['execution_source_sha256']=='58c0a86818d005c6a89c4d12f64475bbade261aa21e79fb17a896a23c5c770fa'
    narrow=read(f'wire-narrow-diff-{lane}.json')
    assert narrow['exactly_expected_narrow_change']
    if lane=='B':
        assert green['raw_wire_sha256']==red['raw_wire_sha256']
        assert green['same_complete_body_as_original_B_replay']
        assert narrow['complete_wire_tree_diff']==[]
    else:
        assert narrow['complete_wire_tree_diff']==[{'path':'$.data.pay_time','kind':'value','red_type':'string','green_type':'string'}]
    cleanup=read('cleanup.json')[lane]
    assert cleanup['worker_stopped'] and cleanup['port_not_listening'] and cleanup['private_lease_released']
    assert cleanup['private_cache_files_remaining']==cleanup['private_runtime_files_remaining']==cleanup['active_temporary_api_auth']==0
    assert cleanup['financial_records_deleted']==0 and cleanup['financial_records_intentionally_retained']
assert read('replay-green-B.json')['wire_shape']==read('replay-green-C.json')['wire_shape']
print('PASS: 10 cash-chain scenarios + red/green refunded-order DB idempotence per engine; source ledgers exact; B wire unchanged/C only pay_time; financial chain retained; credentials/runtime reclaimed; added interface count 0')
