#!/usr/bin/env python3
"""One original bind and one idempotent repeat, not device sync coverage."""
import hashlib
import json
from pathlib import Path
import subprocess
import integrate_20261010 as tool
from integrate_20261011_batches46_48 import item
from integrate_20261013_batch202 import shape

HERE = Path(__file__).resolve().parent
PRIVATE = Path('/private/tmp/cdx-ai-hk-course-b.Kmdirn/meal215-terminal-staff-bind')
BASE = 'work_ai_api/2026-09-30-dm8-interface-acceptance/parallel-terminal-staff-bind-20261013/'


def verify():
    for name, digest in {
        'REPORT_215.md': '6b9232f92d52bc3d3cf90ab172aa57658c6a1c71b7da069a8e7195b1f631c962',
        'verify215_offline.php': 'c526ba5e16280832728adcc826bff001795e70840dde3583fc04e4e71a97c29d',
        'B-business-receipt.json': '923475a3eb7b242e6ab3ee2fa0578e314bc846bf325564f073b3df64df3d342b',
        'C-business-receipt.json': 'b9877cc0cee7cf5bb21039838151cbb03ce3d543de44c35b62547f03586d7ce3',
    }.items():
        assert hashlib.sha256((PRIVATE / name).read_bytes()).hexdigest() == digest
    result = json.loads(subprocess.check_output(['/opt/homebrew/opt/php@7.4/bin/php', str(PRIVATE / 'verify215_offline.php')]))
    assert result['status'] == 'verified' and result['original_POST_total'] == 4
    bodies = {}
    for lane, staff, actor in [('B', 46341, 10080), ('C', 1858, 10016)]:
        receipt = json.loads((PRIVATE / f'{lane}-business-receipt.json').read_text())
        events = {e['phase']: e['data'] for e in receipt['events']}
        before = receipt['source_before']
        after = events['after_first_readback']['source_after']
        assert len(before['staff'][0]) == len(after['staff'][0]) == 21
        assert shape(before['staff']) == shape(after['staff']) and before['staff'] == after['staff']
        assert before['relation'] == [] and len(after['relation']) == 1
        relation = after['relation'][0]
        assert len(relation) == 6 and relation['staff_id'] == staff
        assert relation['store_user_id'] == actor and relation['store_id'] == 10001 and relation['source'] == 1
        assert shape(after) == shape(events['after_repeat_readback']['source_after'])
        assert after == events['after_repeat_readback']['source_after']
        for label in ['first_insert', 'repeat_idempotent']:
            event = events['http_result_' + label]
            assert event['path'].split('?')[0] == '/terminal/store.Staff/bind'
            body = json.loads(event['raw_response_exact'])
            assert isinstance(body['data'], list) and body['data'] == []
            body.pop('trace_id')
            bodies[lane, label] = body
    assert all(shape(body) == shape(bodies['B', 'first_insert']) and body == bodies['B', 'first_insert'] for body in bodies.values())


if __name__ == '__main__':
    audit = HERE / 'integration-20261013-batch215.json'
    assert not audit.exists(), 'Do not replay matrix integration'
    specs = [item('ai_api', 'POST', '/terminal/store.Staff/bind', BASE,
        success_case='partial-evidence-original-owned-staff-bind-first-insert-and-idempotent-repeat',
        readback='tested-pass-real-relation-I1-then-zero-DML-full-Staff-User-actor-unchanged',
        parity='partial-evidence-four-original-JSON-full-keys-values-types-equal-except-trace',
        cleanup='marked-staff-and-relation-retained-private-token-zero-no-device-or-external')]
    tool.main(specs, audit, verify)
