#!/usr/bin/env python3
"""Actual owned Disease POST write/read, retaining the first source-oracle error."""
import hashlib
import json
from pathlib import Path
import subprocess
import sys
import integrate_20261010 as tool
from integrate_20261011_batches46_48 import item
from integrate_20261011_batch85 import semantic_equal

BASE = tool.AI + 'parallel-ai-customer-next-owned-source-20261011/'

def verify():
    root = tool.ROOT / BASE
    assert hashlib.sha256((root / 'manifest.json').read_bytes()).hexdigest() == '67e6dc0c5c2dfc08c7c5261baa8ab3bbbb2282381ec3a09c01b60ea1d356ec15'
    result = json.loads(subprocess.run([sys.executable, '-B', str(root / 'execution/audit.py')],
        check=True, capture_output=True, text=True).stdout)
    assert result['checks'] == 1004
    for lane, sql in [('B', 217), ('C', 307)]:
        facts = result['lanes'][lane]
        assert facts['HTTP'] == facts['formal_INSERT'] == 2
        assert facts['prepare_DML'] == facts['formal_UPDATE'] == facts['DELETE'] == facts['DDL'] == 0
        assert facts['total_SQL'] == sql and facts['protection'] and facts['resources_cleaned']
        assert facts['first_W1_oracle_error_preserved'] and facts['source_corrected_full_W1_pass']
        assert facts['R1_first_frozen_full_DTO_pass']
    seals = json.loads(subprocess.run([sys.executable, '-B', str(root / 'execution/verify_seal.py')],
        check=True, capture_output=True, text=True).stdout)
    assert seals['all_seals_immutable'] and seals['verified_assets'] == 1069
    raw = Path('/tmp/cdx-ai-disease-owned-flow-20261011')
    for label in ['W1_DISEASE_EDIT', 'R1_DISEASE_INFO']:
        body = {}
        for lane in ['B', 'C']:
            record = json.loads((raw / ('private-' + lane + '-final') / ('response-' + label + '.json')).read_text())
            body[lane] = json.loads(record['raw_response_body'])
            assert isinstance(body[lane]['trace_id'], str) and body[lane]['trace_id']
        body['C']['trace_id'] = body['B']['trace_id']
        assert semantic_equal(body['B'], body['C'])
    pins = json.loads((root / 'execution/source-frozen-sha.json').read_text())['files']
    assert len(pins) == 6168
    for relative, digest in pins.items():
        assert hashlib.sha256((tool.ROOT.parent / 'zhctproject/ai_api' / relative).read_bytes()).hexdigest() == digest

def targets():
    return [item('ai_api', 'POST', '/api/user.Disease/' + action, BASE,
        request_type='application/json-form' if action == 'edit' else 'application/json-empty-object',
        scope='customer-AI-own-user_disease-and-habit-nonempty-write-read-with-Bind0-no-Store-run',
        risk='owned-disease-habit-original-two-committed-inserts-no-whole-edit-transaction-claim',
        success_case='partial-evidence-two-POST-nonempty-own-relations-original-oracle-error-preserved-and-source-corrected',
        parity='partial-evidence-two-complete-JSON-semantic-pairs-equal-only-validated-trace_id-mapped',
        duplicate_retry='not-tested',
        boundary_empty_min_max='partial-evidence-type4-habit3-and-OtherInfo0-only',
        cleanup='two-owned-marked-relations-retained-old-weight-nine-and-funds-prepay-unchanged-tokens-workers-cache-released')
        for action in ['edit', 'info']]

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