#!/usr/bin/env python3
"""One-time registration of owned store dish soft-delete, preserving tool failures."""
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-store-dish-delete-20261012/'


def verify():
    for name, digest in [
        ('MANIFEST_178.json', '742140456632286148a730e10f1b8dcba4a39afb0a3f52a0fa2fc3550567b597'),
        ('REPORT_178.md', '35020c1e0b07b622ae7607e3dc8af22fd411131a205fa27179ecad80f043b705'),
        ('verify_owned_delete.php', '4c9f29bc4cdc96671d688e6293010b349113bf3d0b20db92087cf151e5d9c31c'),
    ]:
        assert hashlib.sha256((PRIVATE / 'meal178-store-delete' / name).read_bytes()).hexdigest() == digest
    result = json.loads(subprocess.check_output(['/opt/homebrew/opt/php@7.4/bin/php',
        str(PRIVATE / 'meal178-store-delete/verify_owned_delete.php')]))
    assert result['status'] == 'verified_178_store_owned_delete_BC'
    assert result['actual_business_http_attempts'] == {'B': 2, 'C': 1}
    assert result['B_private_tool_error_http'] == 1 and result['C_rolled_back_setup_attempts'] == 9
    for case in result['cases'].values():
        assert case['setup_committed_rows'] == 9 and case['business_soft_updates'] == 2
        assert case['auth_cleanup_rows'] == 6 and case['auth_fresh_remaining'] == 0
        assert case['real_external_calls'] == 0 and case['old169_rows_unchanged']
    bodies = []
    for name in [
        'runtime/meal178-delete-http-v2-B-a2c60f3a6fb55e47fc4285efe764dbd0bad50199d44d8fe97757f974df418025.json',
        'meal178-store-delete/C_business_success.json',
    ]:
        events = {e['phase']: e for e in json.loads((PRIVATE / name).read_text())['events']}
        event = events['after_http']
        assert event['method'] == 'POST' and event['path'] == '/store/dishes.Dishes/delete'
        request = json.loads(event['request_body_exact'])
        assert type(request['id']) is int
        assert request == {'id': int(events['final_original_table_audit']['own_dish_row_after'][0]['id'])}
        raw = event['raw_response_exact']
        assert hashlib.sha256(raw.encode()).hexdigest() == event['raw_response_sha256']
        body = json.loads(raw)
        body.pop('trace_id', None)
        assert type(body) is dict and type(body['data']) is list
        assert type(body['status']) is int and body == {'status': 200, 'message': '删除成功', 'data': []}
        bodies.append(body)
    assert bodies[0] == bodies[1] and shape(bodies[0]) == shape(bodies[1])


if __name__ == '__main__':
    audit = HERE / 'integration-20261012-batch178.json'
    assert not audit.exists()
    specs = [item('ai_api', 'POST', '/store/dishes.Dishes/delete', BASE,
        risk='own-nonsuper-single-api-role-chain-owned-dish-image-soft-delete-Baidu-hard-stub',
        readback='tested-pass-own-dish-and-image-two-soft-updates-only-time-extra-file-and-old169-relations-unchanged',
        success_case='partial-evidence-owned-dish-with-one-active-image-delete',
        parity='partial-evidence-native-wire-object-array-and-leaf-types-values-equal-except-trace',
        cleanup='six-own-auth-rows-cleaned-tokens-zero-three-synthetic-business-rows-retained-no-real-external')]
    tool.main(specs, audit, verify)
