#!/usr/bin/env python3
"""Unpaid empty-goods cancellation. Secondary User source contract remains open."""
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_batches221_223_224_226 import shape, wire

HERE = Path(__file__).resolve().parent
ROOT = Path('/Users/wiscourper/Documents/workspace/local/dm8-sealed-ai-20261013.4PoFa9/meal230-unpaid-cancel')
BASE = tool.AI + 'parallel-unpaid-cancel-20261013/'


def verify():
    for name, digest in {
        'REPORT_230.md': 'f9985d77af3478cf28e2294972a865738c19bd875c8cbdd45240607acf6bf94a',
        'verify230_offline.php': 'c0e42c054af3868b9bb92e6a3f4f83c03e48f2bce9c69569b8c2c41751db79f6',
        'run230-B.json': '7958483a14e09312152fc00d73913205861d5b7a70331a5695840e2d30ae4d4f',
        'run230-C.json': 'ae55c6f0811e3cb236b8d47b736604cc5668497373a4ee66c9f796e3ceca9713',
    }.items():
        assert hashlib.sha256((ROOT / name).read_bytes()).hexdigest() == digest
    subprocess.run(['/opt/homebrew/opt/php@7.4/bin/php', str(ROOT / 'verify230_offline.php')], check=True, capture_output=True)
    bodies = []
    for lane in ('B', 'C'):
        run = json.loads((ROOT / f'run230-{lane}.json').read_text())
        e = {x['stage']: x for x in run['events']}
        a, b = e['before_http']['order_before'], e['independent_readback']['order_after']
        assert len(a) == len(b) == 37 and set(a) == set(b) and shape(a) == shape(b)
        assert {k for k in a if a[k] != b[k]} <= {'order_status', 'update_time'}
        assert type(a['order_status']) is int and a['order_status'] == 10 and b['order_status'] == 20
        assert e['independent_readback']['private_runtime_sql']['table_hits']['YDY_USER'] > 0
        body = wire(e['original_http'])
        assert type(body['data']) is list and body['data'] == []
        bodies.append(body)
    assert bodies[0] == bodies[1] and shape(bodies[0]) == shape(bodies[1])


if __name__ == '__main__':
    audit = HERE / 'integration-20261013-batch230.json'
    assert not audit.exists(), 'Never replay integration main'
    tool.main([item('ai_api', 'POST', '/api/order/cancel', BASE,
        success_case='partial-evidence-unpaid-empty-goods-order-original-cancel-not-real-stock-or-paid-refund',
        readback='tested-pass-own-AI-order-full37-only-status-update-Store-secondary-User-contract-open',
        parity='partial-evidence-full-original-response-types-values-except-trace-secondary-read-not-fully-verified',
        cleanup='marked-fixture-order-retained-private-token-worker-zero-no-external-call')], audit, verify)
