#!/usr/bin/env python3
"""Keep the single-engine Weight attempt limited after its write scope expanded."""
import hashlib
import json
import re
from pathlib import Path
import integrate_20261010 as tool
from integrate_20261011_batches46_48 import item

HERE = Path(__file__).resolve().parent
PRIVATE = tool.ROOT.parent / 'worktrees/dm8-compat-20261012/private-prepay-harness/batch165-weight-add'
BASE = 'work_store/apifox/2026-09-30-dm8-interface-acceptance/parallel-weight-branch-investigation-20261012/'


def verify():
    report = PRIVATE / 'PAUSED_REPORT.md'
    assert hashlib.sha256(report.read_bytes()).hexdigest() == '49889a9b06da030e77080ae0169c08036c428378f781a216723f6655ba79afd8'
    for name, digest in re.findall(r'\| `([\w.-]+)` \| `([0-9a-f]{64})` \|', report.read_text()):
        assert hashlib.sha256((PRIVATE / name).read_bytes()).hexdigest() == digest
    read = lambda name: json.loads((PRIVATE / name).read_text())
    b = read('B-weight165-http-receipt.json')
    c = read('C-weight165-stopped-state.json')
    assert b['actual_http_count'] == 1 and b['http_status'] == 200 and b['code'] == 0
    assert b['source_match'] is False
    assert all(value == 0 for value in b['related_counts_before'].values())
    assert b['related_counts_after'] == {'MEMBER_WEIGHT': 1, 'MEMBER_WEIGHT_STATUS': 1,
        'USER': 0, 'STAFF_DEPARTMENT': 0, 'RPE': 1, 'MENU_RECOMMEND': 1}
    assert read('B-weight165-add.raw') == {'code': 0, 'message': '添加成功'}
    for name in ['B-weight165-side-effect-audit.json', 'B-weight165-side-effect-provenance.json']:
        assert read(name)['counts'] == {'rpe': 1, 'rpe_info': 2, 'menu_recommend': 1,
            'menu_recommend_record': 0, 'menu_recommend_set': 0}
    assert c['status'] == 'setup-only-unchanged' and c['matches_staff_setup_sha256']
    assert c['business_http_sent'] is False and c['dml'] == c['ddl'] == 0
    assert all(value == 0 for value in c['own_related_counts'].values())


if __name__ == '__main__':
    audit = HERE / 'integration-20261012-batch165.json'
    assert not audit.exists()
    specs = [item('store', 'POST', '/p/weight/add', BASE,
        risk='owned-zero-height-read-type-branch-unexpected-extra-owned-RPE-menu-writes',
        mysql_state='partial-evidence-B-only-HTTP-success-but-preapproved-write-scope-expanded',
        dm_state='not-tested-C-stopped-after-setup-no-business-HTTP',
        mysql_readback='partial-evidence-B-Staff-weight-status-plus-RPE1-info2-menu1',
        dm_readback='not-tested-business-write-only-setup-Staff-unchanged-related-counts-zero',
        readback='partial-evidence-B-expanded-own-writes-C-setup-only-no-HTTP-no-replay',
        success_case='partial-evidence-B-only-not-dual-acceptance-zero-DECIMAL-truthiness-investigation',
        parity='not-compared-C-business-HTTP-not-sent-memory-branch-red-is-separate-evidence',
        cleanup='B-expanded-owned-rows-and-C-setup-retained-no-compensation-or-request-replay')]
    tool.main(specs, audit, verify)
