#!/usr/bin/env python3
"""Four owned backend User CRUD keys; preserve the initial B tool failure."""
import base64
import hashlib
import json
import subprocess
from pathlib import Path
import integrate_20261010 as tool
from integrate_20261011_batches46_48 import item
from integrate_20261012_batch148 import shape

HERE = Path(__file__).resolve().parent
PRIVATE = tool.ROOT.parent.parent / 'local/dm8-store-purchase-read3-20261012.L5dTYR/stage3/user-crud-actual-20261012'
BASE = 'work_store/apifox/2026-09-30-dm8-interface-acceptance/parallel-backend-user-crud-20261012/'


def verify():
    for name, digest in [
        ('REPORT.md', 'af9949da5dcc0322778acb9b068aa8ab4bfcdd24e233b76fac40e89d87c459a8'),
        ('manifest.json', '10b4ad8f4f21584c893df25c5f46f338752bb77713884a343b62a83f9595fa5c'),
        ('verify.js', 'd65107759670b50a5c5291c2e54d8cfffb76218931ffd285725e33ee7f1dce6b'),
        ('audit.json', '7bf4e4dcb9ffa7794c01ef54d54a4f2010b47d7659ce20bec17cfc28849eebb1'),
    ]:
        assert hashlib.sha256((PRIVATE / name).read_bytes()).hexdigest() == digest
    r = json.loads(subprocess.check_output(['node', str(PRIVATE / 'verify.js'), '--readonly']))
    assert r['passed'] and r['checks'] == 1552 and r['assets'] == 120
    assert all(r[k] == 0 for k in ['DB', 'SQL', 'Auth', 'HTTP'])
    source = json.loads((PRIVATE / 'user-source151.json').read_text())
    assert source['HEAD'] == '489d08fd831b6f557a2462bac0fa87ec3dda2a0b'
    for entry in source['files']:
        assert '..' not in Path(entry['path']).parts
        assert hashlib.sha256((tool.source_root('store') / entry['path']).read_bytes()).hexdigest() == entry['sha256']
    bodies = {}
    for lane in ['B', 'C']:
        assert r['side'][lane]['actual_HTTP'] == (5 if lane == 'B' else 4)
        assert r['side'][lane]['begin_attempts'] == (4 if lane == 'B' else 3)
        assert r['side'][lane]['successful_commits'] == 3
        for action in ['A', 'U', 'S', 'D']:
            suffix = 'A2' if lane == 'B' and action == 'A' else action
            p = PRIVATE / lane / ('proof-USERCRUD12W1-' + suffix + '.json')
            proof = json.loads(p.read_text())
            body = json.loads(base64.b64decode(proof['body_base64']))
            assert type(body['code']) is int and body['code'] == 0
            assert body['data'] == ([] if action in ['A', 'S'] else '')
            bodies[lane, action] = body
    for action in ['A', 'U', 'S', 'D']:
        assert bodies['B', action] == bodies['C', action]
        assert shape(bodies['B', action]) == shape(bodies['C', action])


if __name__ == '__main__':
    audit = HERE / 'integration-20261012-batch151.json'
    assert not audit.exists()
    specs = [item('store', 'POST', '/p/user/' + action, BASE,
        risk='owned-nonprivileged-future-validity-backend-user-create-update-status-delete-no-subject-login',
        readback='tested-pass-full40-fields-native-types-original-lastID-DML-transactions-and-nine-references',
        success_case='partial-evidence-single-owned-account-lifecycle-B-first-tool-zero-write-failure-preserved',
        parity='partial-evidence-original-response-values-and-data-array-versus-string-preserved',
        cleanup='own-user-nine-references-zero-original-actor-config-ACL-preserved-workers-and-actor-auth-retained')
        for action in ['add', 'update', 'status', 'delete']]
    tool.main(specs, audit, verify)
