#!/usr/bin/env python3
"""Recharge, payment, refund and device payment-result scoped evidence."""
import hashlib
import json
import subprocess
from decimal import Decimal
from pathlib import Path
import integrate_20261010 as tool
from integrate_20261011_batches46_48 import item
HERE=Path(__file__).resolve().parent
BASE='work_store/apifox/2026-09-30-dm8-interface-acceptance/parallel-prepay-code-scan-20261012/'
REPORT=BASE+'PREPAY_BALANCE_REFUND_10001_BC_20261012.md'
PINS=json.loads(r'''{"B-code-receipt.json":"e42bc22cdb4885def79a23822501111b501860d58874fbd4c1caaab05addff17","C-code-receipt.json":"7653b9401b20485051b8cfd94e37f382311c0707fade8f0ecf3c79a7a4f8fe47","B-scan-receipt.json":"dfaab29266120236bc743bb5612673882c33f7f9f40b21afa44f981c4be35bb7","C-scan-failed-receipt.json":"86e9714e2c632b577e0980924be8db9b63110a43a3e56fb91c650d794bdb55f0","C-scan-retry-receipt.json":"677b85c2b83692839287f67e4c6baf276999ccb674891e5f6d013785f579eb28","C-expire-owned-receipt.json":"6575d3217394141e549847c1f8cbbd4c0dfcf099c9990220f6d82e9c1e64f05c","B-fixture10001-receipt.json":"0fa5ac53f9cae2c1566ade7570c74c9c90398a4951f3596ff5b7d85777a6436b","C-fixture10001-receipt.json":"6060fe4ab8bc6b2497ddda650356ce9802d0b72cdd4bdf3b20d2dd089eb0d1fe","B-fixture10001-recharge-receipt.json":"841228d1a7ee4aa8d4ed67b86de6ec61e7749b468bd3aa7436013199e63e3b30","C-fixture10001-recharge-receipt.json":"b3efc0e37c9add0eb15b774b9250043b8e988214666e3bd6dc258f72f620030e","B-refund-code-receipt.json":"5646ffdd379ebe8b2b74a47eee8b635edd16f7570333d995100e90c8db1dc156","C-refund-code-receipt.json":"4109930c76452e81a8b99f868d3b2e5cd9d72211c2d3ca03b1e98c43ece80fc3","B-refund-scan-receipt.json":"d9384b44bf9b609389e96d7737a845c6f71012daa3fbc7602f53bfbf14bb7bdf","C-refund-scan-receipt.json":"7ce5581ca9cb4e3d44fc2b6ea0c864cb8bbebea37d75d2f911fcaa5e3da5bfbe","B-refund-balance-pay-receipt.json":"9f27c4cd55d035afbfeca1d17d29276dba96b31f125509036f1f51ebc2e00197","C-refund-balance-pay-receipt.json":"dd1a3a283a68833032fb73079ab02fd9383b6b66b1816cf63181b2c2053a39d5","B-duplicate-pay-receipt.json":"02e183e32762a149e10f1ecd20b236d59efe742284daea2ec688372863dc2516","C-duplicate-pay-receipt.json":"21c3b414fff907d8132490fb7b7f369c2143f210180f2cc6504d87a909f666b1","B-pay-refund-receipt.json":"0b12d49745751525102a44f995ac2917e9e2ce2f471dd3f317742943479357d2","B-refund10001-receipt.json":"47f51f4b93d7ea94a14cf54e2284ce25407b305f6ba1d6c4be4fb30426a0e2d3","B-refund10001-correction-receipt.json":"7afc568449db9490cdbdde347b2f92e5902491d593cc55cc0a6efddad7628fac","C-refund10001-receipt.json":"ffaf4639e6932734f7c415e01f3aa7b7bf3db9a7689db495c2e11670529a20d5","B-payresult-receipt.json":"2be4d9e24b1d9ea84b1652b0e3034f70c02eb8bcdd9e3841af040c70b01b75c5","C-payresult-receipt.json":"43811c6d2fbce1a6e3d86e65dfbf27df268dfc0009769c03503b4777ff679bc4"}''')
def verify():
    data={}
    for name,pin in PINS.items():
        raw=(tool.ROOT/BASE/name).read_bytes()
        assert hashlib.sha256(raw).hexdigest()==pin
        data[name]=json.loads(raw)
    r=json.loads(subprocess.check_output(['docker','exec','zhctapp_v2_0','/usr/local/php7.3/bin/php','/workspace/zhct/zhctprompt/'+BASE+'verify_receipts.php']))
    assert r['B_C_10001_recharge_payment_refund'] and r['B_C_duplicate_payment_rejected_without_write'] and r['B_C_prepay_payResult_readback']
    normalized=[]
    for side in ['B','C']:
        credit=data[side+'-fixture10001-recharge-receipt.json']
        assert credit['http_status']==200 and credit['response_code']==0 and credit['recharge_rows_before']==0 and credit['recharge_rows_after']==1
        assert Decimal(credit['wallet_cash_before'])==0 and Decimal(credit['wallet_cash_after'])==Decimal('0.05') and Decimal(credit['cash_log_money'])==Decimal('0.05')
        refund=data[side+'-refund10001-receipt.json']
        assert refund['apply_http']==refund['agree_http']==200 and refund['apply_code']==refund['agree_code']==0
        assert Decimal(refund['wallet_cash_before'])==Decimal(refund['wallet_cash_after_apply'])==Decimal('0.04')
        assert Decimal(refund['wallet_cash_after_agree'])==Decimal('0.05')
        assert refund['refund_rows_before']==0 and refund['refund_rows_after_agree']==1
        assert refund['refund_status_after_agree']==2 and refund['meal_refund_status_after_agree']==3
        assert refund['refund_settlement_rows']==1 and refund['refund_settlement_status']==20
        assert Decimal(refund['refund_settlement_cash'])==Decimal(refund['meal_cash_refund_amount_after_agree'])==Decimal('0.01')
        raw=json.loads((tool.ROOT/BASE/(side+'-refund10001-apply.raw')).read_text())
        assert type(raw['data']['refund_id']) is str and raw['data']['refund_id']==str(refund['refund_id'])
        raw['data']['refund_id']='<own-refund>'
        normalized.append(json.dumps(raw,sort_keys=True))
        query=data[side+'-payresult-receipt.json']
        assert query['passed'] and query['request_roundtrip'] and query['meal_exact_unchanged'] and query['wallet_exact_unchanged']
        assert query['prepay_status_before']==query['prepay_status_after']==1 and query['settlement_count_before']==query['settlement_count_after']==2
    assert normalized[0]==normalized[1]
    assert (tool.ROOT/BASE/'B-refund10001-agree.raw').read_bytes()==(tool.ROOT/BASE/'C-refund10001-agree.raw').read_bytes()
    assert not data['B-refund10001-receipt.json']['passed']
    assert data['B-refund10001-correction-receipt.json']['correction_type']=='test-assertion-only-no-http-no-dml'
def targets():
    out=[]
    for repo,path in [('store','/p/rechargeOrder/add'),('store','/p/mealOrder/refund'),('store','/p/mealOrder/refundAgree'),('ai_api','/api/MealCashier/orderPay'),('store','/api/prepayOrder/payResult')]:
        out.append(item(repo,'POST',path,BASE,evidence=REPORT,
            readback='partial-evidence-owned-10001-cash-0.00-to-0.05-to-0.04-to-0.05-order-settlement-refund-and-cash-ledgers',
            success_case='partial-evidence-actual-internal-cash-recharge-payment-refund-and-signed-device-query-no-third-party',
            parity='partial-evidence-cash-strings-and-recorded-payment-types-refund-raw-body-compared-success-payment-full-body-not-saved',
            duplicate_retry='partial-evidence-paid-order-repeat-payment-rejected-with-wallet-order-ledgers-unchanged',
            cleanup='marked-fixtures-retained-old-mismatched-tenant-refund-and-test-assertion-failure-preserved'))
    for repo,path in [('store','/api/prepayOrder/code'),('ai_api','/api/PrepayOrder/scan')]:
        out.append(item(repo,'POST',path,BASE,evidence=REPORT,evidence_only=True))
    return out
if __name__=='__main__':
    audit=HERE/'integration-20261012-batch115.json';assert not audit.exists()
    tool.main(targets(),audit,verify)
