#!/usr/bin/env python3
"""Offline regression verification of the new RP/RM API-owned rows."""
import hashlib
import json
from pathlib import Path

root = Path(__file__).parent / 'private-evidence'
summary = {'HTTP': 0, 'actual_DML': 0, 'framework_prepared': 0, 'lanes': {}, 'passed': True}
def read(path):
    return json.loads(path.read_text())
def check(ok, why):
    if not ok:
        raise AssertionError(why)
for lane in ('B', 'C'):
    directory = root / (lane + '-noop')
    baseline, lease = read(directory / 'baseline.json'), read(directory / 'lease.json')
    ownids = {str(row['id']) for row in lease['nutrition_category']}
    cases = []
    for side in ('P', 'M'):
        for step in (1, 3, 4, 5):
            label = f'R-{side}{step}'
            wire, result = read(directory / (label + '.wire.json')), read(directory / (label + '.result.json'))
            body = json.loads(wire['body'])
            check(wire['status'] == 200 and result['HTTP'] == 200, 'Real HTTP200')
            check(wire['body'] == result['body'] and hashlib.sha256(wire['body'].encode()).hexdigest() == result['body_sha256'], 'Original response bytes')
            check(wire['source_after'] == result['independent_after'], 'Independent PDO after')
            check(body == {'code': 1, 'message': '状态修改失败', 'data': []} if step == 4 else body['code'] == 0, 'Original response contract')
            for source in (wire['source_before'], wire['source_after']):
                for key in ('staff_sha256', 'user_sha256', 'actor_sha256'):
                    check(source[key] == baseline[key], 'Complete original identity')
                check(source['material_category'] == baseline['material_category'], 'All original and retained3 material rows exact')
                check([row for row in source['nutrition_category'] if str(row['id']) not in ownids] == baseline['nutrition_category'], 'All original and read9 nutrition rows exact')
            dml = [sql for sql in wire['prepared_SQL'] if sql['queryString'].lstrip().split(' ')[0].upper() in ('INSERT', 'UPDATE', 'DELETE')]
            check(len(dml) == 1 and dml[0].get('ok') is True and wire['remaining_allowances'] == [], 'Exact one completed DML')
            check(dml[0]['rowCount'] == (0 if step == 4 else 1), 'Real rowCount0/1')
            if lane == 'C' and step in (3, 4):
                check('`status` <>' in dml[0]['queryString'] and 'where_and_status' in dml[0]['bindings'] and str(dml[0]['bindings']['where_and_status']['value']) == '0', 'Real DM atomic status<>0 prepared binding')
            if lane == 'B' and step in (3, 4):
                check('<>' not in dml[0]['queryString'], 'MySQL original update untouched')
            if step == 4:
                check(wire['source_before'] == wire['source_after'], 'Repeat changes zero complete source values')
            cases.append({'label': label, 'code': body['code'], 'rowCount': dml[0]['rowCount'], 'originals_stable': True})
            summary['HTTP'] += 1
            summary['actual_DML'] += 1
            summary['framework_prepared'] += len(wire['prepared_SQL'])
    final = read(directory / 'final.json')
    check(final['own_nutrition_count'] == 0 and final['own_material_count'] == 3 and final['all_material_softdeleted'], 'Final fixture retention')
    summary['lanes'][lane] = {'cases': cases, 'final_new_nutrition': 0, 'original_and_retained_material_rows_stable': True}
check(summary['HTTP'] == summary['actual_DML'] == 16, 'Approved16HTTP')
print(json.dumps(summary, ensure_ascii=False, indent=2))
