import json
from pathlib import Path
p = Path(__file__).parent
read = lambda name: json.loads((p / name).read_text())
b, c = [read(f'result-{lane}.json') for lane in 'BC']
expected = [('apply_first', 0), ('reject_success', 0), ('reject_immediate_cache', 1), ('reject_after_own_cache_clear', '2'), ('apply_again', 0), ('reject_missing', '2')]
for report in (b, c):
    assert report['failure'] is None
    assert [(x['scenario'], x['code']) for x in report['cases']] == expected
    assert report['apply_id_observation']['response_type'] == 'string'
    assert report['apply_id_observation']['id_decimal_text_equal']
    assert report['audit_source'] == {'rows': 3, 'apply_events': 2, 'reject_events': 1, 'identity_action_target_context_path_time_trace_defaults_verified': True}
    cleanup = report['cleanup']
    assert [cleanup[x] for x in ('own_refunds_deleted','own_audits_deleted','own_orders_deleted','own_stalls_deleted')] == [2,3,1,1]
    assert [cleanup[x] for x in ('remaining_own_orders','remaining_own_refunds','remaining_own_stalls')] == [0,0,0]
    assert cleanup['both_business_databases_wallet_sources_unchanged']
    assert report['wallet_source_before'] == report['wallet_source_after']
for x, y in zip(b['cases'], c['cases']):
    assert (x['method'],x['path'],x['scenario']) == (y['method'],y['path'],y['scenario'])
    assert x['wire_shape'] == y['wire_shape']
    assert x['normalized_wire_sha256'] == y['normalized_wire_sha256']
for lane in 'BC':
    audit = read(f'independent-audit-{lane}.json')
    assert audit['all_passed'] and audit['independent_new_connections'] and audit['database_writes'] == 0
    assert set(audit['remaining_owned_rows'].values()) == {0}
    assert all(x['same_before'] for x in audit['wallet_sources'].values())
    assert all(x['matches_frozen'] for x in audit['source_sha256'].values())
    missing = read(f'positive-missing-{lane}.json')
    assert missing['all_passed'] and missing['positive_id_independently_absent']
    assert missing['both_business_databases_sources_unchanged'] and missing['database_writes'] == 0
assert read('positive-missing-B.json')['full_raw_wire_sha256'] == read('positive-missing-C.json')['full_raw_wire_sha256']
for cleanup in read('cleanup.json').values():
    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'] == 0
print('PASS: 6 write-chain + 1 positive missing-ID DB-read scenes each engine; full wire equal; three audits; ten wallet/source sets unchanged; independent own-four-table zero + worker/cache/lease cleanup')
