#!/usr/bin/env python3
"""Record original core payment evidence without hiding its physical/DTO gaps."""
import hashlib
import json
from pathlib import Path
import stat
import subprocess
import sys
import integrate_20261010 as tool
from integrate_20261011_batches46_48 import item

BASE=tool.AI+'parallel-ai-core-scan-pay-20261011/'
PIN='cfda90d3fb84df1c73920f7b831c64d85e28bdfbd4a4b965086fe05a96d57b15'
PRIVATE=Path('/tmp/cdx-ai-core-scan-pay-20261011')

def verify():
    root=tool.ROOT/BASE
    assert hashlib.sha256((root/'manifest.json').read_bytes()).hexdigest()==PIN
    manifest=json.loads((root/'manifest.json').read_text())
    total=0
    groups=[(root,manifest['public_files'])]
    for lane,group in manifest['canonical_private_groups'].items():
        expected=PRIVATE/f'private-{lane}-final'
        assert lane in ['B','C'] and Path(group['root'])==expected
        assert not expected.is_symlink() and stat.S_IMODE(expected.stat().st_mode)==0o700
        groups.append((expected,group['files']))
    for parent,files in groups:
        for record in files:
            relative=Path(record['path'])
            assert not relative.is_absolute() and '..' not in relative.parts
            path=parent/relative
            assert not path.is_symlink() and path.is_file()
            body=path.read_bytes()
            assert len(body)==record['bytes'] and hashlib.sha256(body).hexdigest()==record['sha256']
            assert oct(stat.S_IMODE(path.stat().st_mode))==record['mode']
            total+=1
    assert total==208
    result=subprocess.run([sys.executable,'-B',str(root/'verify.py')],capture_output=True,text=True)
    assert result.returncode==0,result.stderr
    report=json.loads(result.stdout)
    assert report['checks']==6674 and report['outcome_counterexamples']==6
    assert report['lanes']['B']['HTTP']==10 and report['lanes']['C']['HTTP']==9
    for lane,label in [('B','PREPAY_FIRST_RETRY'),('C','PREPAY_FIRST_RETRY1')]:
        wire=json.loads((PRIVATE/f'private-{lane}-final'/f'wire-{label}.json').read_text())
        before=wire['own_before']['STORE_P1'][0]
        after=wire['own_after']['STORE_P1'][0]
        changed={key for key in before if before[key]!=after[key]}
        expected={'meal_order_id','meal_order_no','user_id','update_by'}
        if lane=='B':expected.add('update_time')
        assert changed==expected
        assert (before['update_time']!=after['update_time'])==(lane=='B')
    # The missing original success DTO must remain missing even after fresh 0.02.
    c=PRIVATE/'private-C-final'
    assert not (c/'wire-DIRECT_SUCCESS_RETRY1.json').exists()
    assert not (c/'response-before-observers-DIRECT_SUCCESS_RETRY1.json').exists()

def targets():
    return [
        item('ai_api','POST','/api/PrepayOrder/scan',BASE,
             risk='owned-prepay-CAS-update-time-physical-compatibility-gap',
             dm_state='tested-fail-prepay-ONUPDATE-not-applied',
             dm_readback='tested-fail-native-update-time-unchanged-while-source-auto-updates',
             parity='partial-original-success-repeat-other-user-missing-DTO-complete-physical-ONUPDATE-gap-open',
             duplicate_retry='partial-evidence-prepay-same-user-idempotence-only'),
        item('ai_api','POST','/api/mealCheckout/directPay',BASE,
             risk='owned-real-one-cent-wallet-order-settlement-log-two-independent-transactions',
             dm_state='partial-evidence-physical-commit-only-original-success-DTO-not-captured',
             success_case='partial-evidence-B-full-success-and-B-C-committed-ledger-C-original-DTO-missing',
             parity='partial-C-original-success-DTO-missing-not-reconstructed-new-payment-separate',
             duplicate_retry='not-tested-five-second-window-missed-no-success-replay',
             boundary_empty_min_max='partial-evidence-zero-money-and-insufficient-balance-original-HTTP-zero-DML')
    ]

if __name__=='__main__':
    audit=Path(__file__).with_name('integration-20261011-batch78.json')
    assert not audit.exists(),'Preserve original transition audit'
    tool.main(targets(),audit,verify)
