#!/usr/bin/env python3
"""Existing read8 + independent payment-source proof; no secrets or write replay."""
import hashlib
import json
from pathlib import Path
import integrate_20261010 as tool
from integrate_20261011_batches46_48 import item

HERE = Path(__file__).resolve().parent
PRIVATE = Path('/private/tmp/cdx-ai-hk-course-b.Kmdirn')
BASE = 'work_ai_api/2026-09-30-dm8-interface-acceptance/parallel-store-terminal-settings-read-20261012/'


def read(path, digest):
    raw = path.read_bytes()
    assert hashlib.sha256(raw).hexdigest() == digest
    return json.loads(raw)['events']


def verify():
    assert hashlib.sha256((PRIVATE / 'verify_payment_options_source.php').read_bytes()).hexdigest() == '82d6d5ef4ce5e0960433cf4be06beefc78fb9ed0c914e50c8dd9fb9e7fd78d98'
    lanes = []
    for name, digest in [
        ('store-terminal-read8-CDXMOD0E6A7187951C.json', '7fd5b02b318d55ae830511e133ee03344ce7b51b291789afee39b9b1ba2daf0e'),
        ('c-store-terminal-read8-CDXMOD27226526F7BB.json', 'd0d155a4c872783375184fc3c9afdf48d2e41dff85a8e38ebe3c8e536c6567ea'),
    ]:
        events = read(PRIVATE / 'runtime' / name, digest)
        assert events[-1]['token_absent']
        selected = {e['path'].split('?')[0]: e for e in events if 'path' in e and not e['path'].endswith('/Store/info')}
        assert len(selected) == 6
        for path, e in selected.items():
            assert e['method'] == 'GET' and e['http'] == e['business_status'] == 200 and e['pass']
            assert e['source_rows_unchanged'] and e['external_stub_delta_bytes'] == 0
            assert e['source_row_count'] == (9 if 'Payment' in path else None if 'Cache' in path else 0)
        lanes.append(selected)
    for path in lanes[0]:
        assert lanes[0][path]['response_shape'] == lanes[1][path]['response_shape']
        if 'Payment' not in path:
            assert lanes[0][path]['response_normalized_sha256'] == lanes[1][path]['response_normalized_sha256']
    for path, digest in [
        (PRIVATE / 'runtime/payment-source-proof-CDXPAYR08E6DBF9BAAB.json', '1d8c17f9c44cabc8d5bdcce6d74a4ec8f9084116df3e8ec4ec6854099213666c'),
        (Path('/Users/wiscourper/Documents/workspace/local/dm8-batch116-20261012.S1TtvG/payment-source-proof-C-BF8B83EE8106.json'), '3e0c272c394716ece57f4801b3f4f878aefb9b97462c2aef24e5e494ff0fc443'),
    ]:
        events = read(path, digest)
        assert events[0]['source_row_count'] == 9 and events[-1]['token_absent']
        proofs = [e for e in events if 'path' in e]
        assert {e['path'] for e in proofs} == {'/store/setting.Payment/options', '/terminal/setting.Payment/options'}
        for e in proofs:
            assert e['pass'] and e['strict_php_equal'] and e['exact_json_equal'] and e['mismatch_count'] == 0
            assert e['http'] == e['business_status'] == 200 and e['source_rows_after'] == 9
            assert e['source_row_fingerprint_after'] == events[0]['source_row_fingerprint']
            assert e['actual_options_sha256'] == e['expected_options_sha256'] == events[0]['expected_options_sha256']


if __name__ == '__main__':
    audit = HERE / 'integration-20261012-batch132.json'
    assert not audit.exists()
    targets = []
    for app in ['store', 'terminal']:
        targets.append(item('ai_api', 'GET', '/' + app + '/setting.Payment/options', BASE,
            from_repo='unreviewed', from_source='apifox-2026-05-08',
            readback='tested-pass-nine-original-payment-source-rows-independent-RAM-option-values-types-hash',
            parity='partial-evidence-own-snapshot-strict-values-and-types-not-cross-snapshot-value-equality',
            cleanup='readonly-original-source-unchanged-private-token-removed-no-payment-execution'))
        for suffix, scope in [('Setting/detail', 'zero-row-store-key-default-only'), ('setting.Cache/items', 'static-descriptor-no-business-DB')]:
            targets.append(item('ai_api', 'GET', '/' + app + '/' + suffix, BASE,
                from_repo='unreviewed', from_source='apifox-2026-05-08',
                mysql_state='partial-evidence-' + scope, dm_state='partial-evidence-' + scope,
                readback='partial-evidence-zero-row-default' if suffix == 'Setting/detail' else 'not-applicable-no-business-DB',
                parity='partial-evidence-default-or-static-JSON-types-and-normalized-hash-equal',
                cleanup='no-business-writes-private-token-removed-zero-external'))
    tool.main(targets, audit, verify)
