#!/usr/bin/env python3
"""Four customer grade/cash routes; verify frozen receipts before one-time ledger update."""
import hashlib
import json
import subprocess
from pathlib import Path
from urllib.parse import urlsplit, parse_qs
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-customer-grade-cash-20261012/'
FILES = {
    'B_store': 'owned-finance-f948e3d61f0656078a609affc1b8dfcb11257f0cf40179860015d54d055e2c9a.json',
    'C_store': 'C_owned_finance_store_8f94a2b5.json',
    'B_terminal': 'owned-finance-f9f132d66d03228a3b886072558b3e97fccec4a0c8fc4ba7beb78aafd9992b4c.json',
    'C_terminal': 'C_owned_finance_terminal_0d6b4dd9.json',
}


def verify():
    for name, digest in [
        ('CUSTOMER_GRADE_CASH_MANIFEST_20261012.json', '3b6a288b6929946fd74700cf359ba839b1f3ec49d20f71e072fb154d0f740cd3'),
        ('CUSTOMER_GRADE_CASH_BC_20261012.md', '0a19a5b9e920ae02146abb1277005c38eb4535f1bb964c658d299af010c39844'),
        ('run_customer_grade_cash_owned.php', 'b491ad2160afa077245851962134fbefde27a157fa4d40a62dc479aa5e78742c'),
        ('verify_customer_grade_cash_receipts.php', '6a5b0357912dd8cc28f05deb0254c5fd0dfcff4286c93c40c5ce1e22ee126c2b'),
    ]:
        assert hashlib.sha256((PRIVATE / name).read_bytes()).hexdigest() == digest
    r = json.loads(subprocess.check_output(['/opt/homebrew/opt/php@7.4/bin/php', str(PRIVATE / 'verify_customer_grade_cash_receipts.php')]))
    assert r['status'] == 'verified' and r['db_or_http_calls'] == 0
    assert r['true_http_count'] == 8 and r['new_unique_keys'] == 4
    assert r['response_without_trace_all_four_equal'] and r['C_onecard_config_differs_from_B']
    manifest = json.loads((PRIVATE / 'CUSTOMER_GRADE_CASH_MANIFEST_20261012.json').read_text())
    for label, name in FILES.items():
        assert r['targets'][label]['passed'] and all(r['targets'][label]['checks'].values())
        own = manifest['retained_synthetic_audit_ids'][label]
        surface = label.split('_')[1]
        events = json.loads((PRIVATE / 'runtime' / name).read_text())['events']
        http = [e for e in events if e['phase'].startswith('after_http_')]
        assert len(http) == 2
        for e in http:
            action = e['phase'].removeprefix('after_http_')
            url = urlsplit(e['path'])
            assert e['method'] == 'POST' and url.path == '/' + surface + '/User/' + action
            q = parse_qs(url.query)
            assert q['userId'] == [str(own['ai_user_id'])]
            if action == 'recharge':
                assert q['target'] == ['balance']
            wire = json.loads(e['raw_response_exact'])
            assert type(wire['status']) is int and wire['status'] == 200
            assert wire['message'] == '操作成功' and wire['data'] == []
            assert isinstance(wire['trace_id'], str) and wire['trace_id']
        assert r['targets'][label]['grade_log_id'] == own['grade_log_id']
        assert r['targets'][label]['balance_log_id'] == own['balance_log_id']


if __name__ == '__main__':
    audit = HERE / 'integration-20261012-batch142.json'
    assert not audit.exists()
    specs = []
    for surface in ['store', 'terminal']:
        for action in ['grade', 'recharge']:
            specs.append(item('ai_api', 'POST', '/' + surface + '/User/' + action, BASE,
                from_repo='unreviewed', from_source='apifox-2026-05-08',
                risk='owned-customer-grade-or-internal-cash-write-no-external-payment',
                readback='tested-pass-own-user-and-exact-grade-or-balance-ledger-readback',
                success_case='partial-evidence-fresh-owned-customer-grade-0-to-existing-10001' if action == 'grade' else 'partial-evidence-target-balance-inc-0.01-only',
                parity='partial-evidence-whole-business-response-equal-onecard-config-branches-differ',
                cleanup='four-marked-users-and-eight-ledger-rows-retained-temporary-tokens-zero',
                request_type='application/json-form-userId-query-target-balance-for-recharge'))
    tool.main(specs, audit, verify)
