#!/usr/bin/env python3
"""Face core persistence only; Equipment/MQ branches are deliberately not covered."""
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/meal216-terminal-face')
BASE = 'work_ai_api/2026-09-30-dm8-interface-acceptance/parallel-terminal-face-20261013/'


def verify():
    for name, digest in {
        'REPORT_216.md': '03573b87917381f366129143d8c2757f454d638dbeb548eb1a49ac936f78c195',
        'verify216_offline.php': 'eb4cc33ae769dea7fde5d4112fa2eeee9d20f3a4b0ea4e0c07567cf73111f07c',
        'B-business-receipt.json': '98c4a0817d477ce2323c31d5e38df251bff691594d3bc534120bbe33b5f22623',
        'C-business-receipt.json': '41371c7fb856374a7bc1cfc7a94222fdaebd1eb30970e7ce2d085e1a4fab68e5',
    }.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 / 'verify216_offline.php')]))
    assert result['status'] == 'verified-core-partial-external' and result['original_POST_total'] == 4
    bodies = {}
    for lane in ('B', 'C'):
        record = json.loads((PRIVATE / f'{lane}-business-receipt.json').read_text())
        events = {e['phase']: e['data'] for e in record['events']}
        added = events['after_add_readback']['source_after']['face'][0]
        deleted = events['after_delete_readback']['source_after']['face'][0]
        assert len(added) == len(deleted) == 10 and set(added) == set(deleted)
        changes = {k for k in added if type(added[k]) is not type(deleted[k]) or added[k] != deleted[k]}
        assert 'is_delete' in changes and changes <= {'is_delete', 'update_time'}
        for action in ('add', 'delete'):
            event = events['http_result_' + action]
            assert event['path'].split('?')[0] == '/terminal/store.Face/' + action
            body = json.loads(event['raw_response_exact'])
            if action == 'add':
                assert isinstance(body['data'], dict) and set(body['data']) == {'id'}
                assert type(body['data']['id']) is str and body['data']['id'] == str(added['id'])
            else:
                assert isinstance(body['data'], list) and body['data'] == []
            body.pop('trace_id'); bodies[lane, action] = body
        assert events['final_audit']['source_after']['face'] == [deleted]
    for action in ('add', 'delete'):
        assert shape(bodies['B', action]) == shape(bodies['C', action])
        assert bodies['B', action] == bodies['C', action]


if __name__ == '__main__':
    audit = HERE / 'integration-20261013-batch216.json'
    assert not audit.exists(), 'Do not replay matrix integration'
    specs = [item('ai_api', 'POST', '/terminal/store.Face/' + action, BASE,
        success_case='partial-evidence-original-Face-core-owned-synthetic-feature-I1-softU1-no-device-MQ-DB-coverage',
        readback='tested-pass-real-ten-column-Face-owned-relations-and-full-protected-rows-invariant',
        parity='partial-evidence-full-original-JSON-equal-string-generated-ID-and-array-types',
        cleanup='own-virtual-file-and-softdeleted-Face-retained-token-zero-external-boundary-captured-only')
        for action in ('add', 'delete')]
    tool.main(specs, audit, verify)
