#!/usr/bin/env python3
"""Three food writes plus existing detail regression, only private original receipts."""
import hashlib
import json
import subprocess
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-terminal-foods-write-20261012/'


def verify():
    for name, digest in [
        ('run_terminal_foods_write.php', '07abed6180cd3e009a0fd98bffb912f363d9a0a9eeb4c0ab9efa2928551b3ad0'),
        ('verify_terminal_foods_receipts.php', '68132e031ae36de0248f70da65f64d6af0dabcc70cf8caa4d953f159a37bef01'),
    ]:
        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 / 'verify_terminal_foods_receipts.php')]))
    assert result['status'] == 'verified' and result['business_http_or_db_calls'] == 0
    assert result['synthetic_detail_all_fields_except_dynamic_equal'] and result['detail_key_regression_only']
    assert result['new_unique_write_keys'] == 3
    for lane in ['B', 'C']:
        assert result['targets'][lane]['passed'] and len(result['targets'][lane]['checks']) == 9
        assert result['targets'][lane]['detail_json_decimal_type'] == 'string'
    assert result['targets']['B']['source_pdo_decimal_type'] == 'string'
    assert result['targets']['C']['source_pdo_decimal_type'] == 'double'
    for name in ['terminal-foods-write-CDXPARFOODC7183E2B4E.json', 'C_terminal_foods_write_CD9EBF3D662C.json']:
        events = json.loads((PRIVATE / 'runtime' / name).read_text())['events']
        http = [e for e in events if e['phase'].startswith('after_http_')]
        assert len(http) == 4
        for e in http:
            action = e['phase'].removeprefix('after_http_')
            assert e['path'].split('?')[0] == '/terminal/dishes.Foods/' + action
            assert e['method'] == ('GET' if action == 'detail' else 'POST')
            assert json.loads(e['raw_response_exact'])['status'] == 200


if __name__ == '__main__':
    audit = HERE / 'integration-20261012-batch133.json'
    assert not audit.exists()
    targets = [item('ai_api', 'POST', '/terminal/dishes.Foods/' + action, BASE,
        from_repo='unreviewed', from_source='apifox-2026-05-08',
        risk='owned-food-CRUD', request_type='JSON-form-with-decimal-string-inputs',
        readback='tested-pass-owned-food0-to1-same-ID-edit-softdelete-and-four-decimal-inputs-source-match',
        parity='partial-evidence-four-decimal-detail-fixed2-strings-and-synthetic-nondynamic-whole-DTO-equal',
        cleanup='exact-owned-food-removed-links-zero-token-absent-external-zero')
        for action in ['add', 'edit', 'delete']]
    targets.append(item('ai_api', 'GET', '/terminal/dishes.Foods/detail', BASE,
                        evidence_only=True, risk='owned-food-read-decimal-regression'))
    tool.main(targets, audit, verify)
