#!/usr/bin/env python3
"""Terminal rejection branch only, not refund or Store counterpart."""
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/meal227-terminal-sealed')
BASE = tool.AI + 'parallel-terminal-cancel-reject-20261013/'


def verify():
    for name, digest in {
        'REPORT_TERMINAL_227.md': 'bf550cd1ee1048b1cfad1e403fab7e15e9432bac4af4c4961883d62c60a3348b',
        'verify227_terminal_offline.php': '33dbd7d8c625c6e73ea14d8e06a0083f3442ccabe34e6f72424f02c8ed4749f9',
        'run227-terminal-B.json': '2fdca34e0cd4b8131a7032e2a7950d7d8255731113ae27f0c4e8972f10e5f28c',
        'run227-terminal-C.json': '5f6b1d76e133ec4c8f86a5a1e3dadf3a67f5dcef24d47f64c9ca3a176c7176fe',
    }.items():
        assert hashlib.sha256((ROOT / name).read_bytes()).hexdigest() == digest
    subprocess.run(['/opt/homebrew/opt/php@7.4/bin/php', str(ROOT / 'verify227_terminal_offline.php')],
        check=True, capture_output=True)
    bodies = []
    for lane in ('B', 'C'):
        run = json.loads((ROOT / f'run227-terminal-{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'] == 21 and b['order_status'] == 10
        # The C receipt deliberately retains the one OTHER order_type trade
        # with the same numeric order ID; do not wash that protected row to 0.
        assert e['independent_readback']['trade_count'] == (0 if lane == 'B' else 1)
        if lane == 'C':
            assert e['before_http']['own_refund_trade_before_zero'] is True
            assert e['before_http']['same_numeric_order_id_other_type_trade_count'] == 1
        else:
            assert e['before_http']['refund_trade_before_zero'] is True
        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-batch227.json'
    assert not audit.exists(), 'Never replay integration main'
    tool.main([item('ai_api', 'POST', '/terminal/order.event/confirmCancel', BASE,
        success_case='partial-evidence-original-status0-reject-cancel-zero-money-state-fixture-not-refund',
        readback='tested-pass-full37-own-order21-to10-user-finance-protected-no-real-payment',
        request_type='application/json-form-status-integer-zero',
        cleanup='marked-order-retained-private-worker-and-token-zero-no-API-dictionary-write')], audit, verify)
