#!/usr/bin/env python3
"""Verify immutable owned dish/image evidence before one-time matrix integration."""
import hashlib
import json
import subprocess
from pathlib import Path
import integrate_20261010 as tool
from integrate_20261011_batches46_48 import item
from integrate_20261012_batch148 import shape

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-owned-dish-image-20261012/'


def verify():
    path = PRIVATE / 'meal169-owned-dish/MANIFEST_169.json'
    assert hashlib.sha256(path.read_bytes()).hexdigest() == 'bf0fed03f236bbe0eb78c7b3e8f2db75f2f4a43adfc91f29eff82639d3d8be01'
    manifest = json.loads(path.read_text())
    assert len(manifest['assets_sha256']) == 25
    for name, digest in manifest['assets_sha256'].items():
        assert not Path(name).is_absolute() and '..' not in Path(name).parts
        assert hashlib.sha256((PRIVATE / name).read_bytes()).hexdigest() == digest, name
    result = json.loads(subprocess.check_output(['/opt/homebrew/opt/php@7.4/bin/php',
        str(PRIVATE / 'meal169-owned-dish/verify_owned_dish_image_169.php')]))
    assert result['status'] == 'verified_169_three_new_keys_owned_B_C'
    assert result['business_http_actual'] == {'B': 3, 'C': 3, 'total': 6}
    assert result['setup_dml'] == {'B': 1, 'C': 1}
    for case in result['cases'].values():
        assert case['fourbyte_name_exact'] and case['dish_weight_scale2_match']
        assert case['real_baidu_qw_queue_calls'] == 0 and not case['physical_file_created']
    pairs = [
        ('runtime/meal169-dish-add-v2-78524c8682e8e6e189d63437b9132229c0084eb08ee646d0c37dadf5264a4774.json',
         'meal169-owned-dish/C_dish_add.json', ['after_http']),
        ('runtime/meal169-img-add-delete-2dd8eac89ee86289e478c96b74f430ec7794c3fe1864d619d7b09b489711c84e.json',
         'meal169-owned-dish/C_img_add_delete.json', ['after_http_img_add', 'after_http_img_delete']),
    ]
    for b, c, phases in pairs:
        events = [{e['phase']: e for e in json.loads((PRIVATE / name).read_text())['events']} for name in (b, c)]
        for phase in phases:
            bodies = []
            for side in events:
                raw = side[phase]['raw_response_exact']
                assert hashlib.sha256(raw.encode()).hexdigest() == side[phase]['raw_response_sha256']
                body = json.loads(raw)
                assert type(body['status']) is int and body['status'] == 200
                body.pop('trace_id', None)
                if phase in ('after_http', 'after_http_img_add'):
                    assert type(body['data']['id']) is str
                    body['data']['id'] = '{own_id}'
                bodies.append(body)
            assert bodies[0] == bodies[1] and shape(bodies[0]) == shape(bodies[1])


if __name__ == '__main__':
    audit = HERE / 'integration-20261012-batch169.json'
    assert not audit.exists()
    specs = []
    for path in ['/terminal/dishes.Dishes/add', '/terminal/dishes.Img/add', '/terminal/dishes.Img/delete']:
        specs.append(item('ai_api', 'POST', path, BASE,
            risk='own-dish-image-write-real-disabled-operator-private-auth-exact-Baidu-hard-stub',
            success_case='partial-evidence-owned-positive-create-or-soft-delete-only',
            readback='tested-pass-own-Dish-INSERT1-Img-INSERT1-soft-UPDATE1-exact-association-other-source-rows-unchanged',
            parity='partial-evidence-full-wire-values-and-object-array-leaf-types-equal-except-trace-own-id',
            boundary_empty_min_max='partial-evidence-fourbyte-dish-name-and-scale2-weight' if path.endswith('Dishes/add') else 'not-tested',
            cleanup='synthetic-rows-retained-token-zero-real-external-and-physical-file-zero'))
    tool.main(specs, audit, verify)
