#!/usr/bin/env python3
"""Root evidence-only enhancement of the three previously measured Rope keys."""
import importlib
import json
from decimal import Decimal
from pathlib import Path
import re
import sys
import integrate_20261010 as tool
from integrate_20261011_batches40_42 import run, sha
from integrate_20261011_batches46_48 import item

BASE = tool.AI + 'parallel-ai-rope-exact-http-20261011/'
PIN = '29ca65b5859a2dda4a1484edca0a8bf0ca86b7be733881ef1d9a74da81f1a47a'

def verify():
    root = tool.ROOT / BASE
    assert sha(root / 'manifest.json') == PIN
    seal = json.loads(run(BASE, sys.executable, 'seal.py', '--verify'))
    assert seal == {'seal_valid': True, 'public_files': 35, 'private_files': 132}
    sys.path.insert(0, str(root))
    try:
        v = importlib.import_module('verify')
        result = v.all_verify()
        assert [r['actual_HTTP'] for r in result['lanes']] == [21, 20]
        assert [r['actual_native_execute'] for r in result['lanes']] == [229, 439]
        assert not result['main_whole_source_drift'] and result['new_interface_keys'] == 0
        for lane in 'BC':
            private = root / 'private' / ('C' if lane == 'C' else '')
            cases = v.load(root / ('cases-retry.json' if lane == 'B' else 'cases.json'))
            originals = v.load(root / 'cases.json')
            for name in list(cases) + (['ADD_A'] if lane == 'B' else []):
                wire = v.load(private / f'wire-{name}.json')
                client = v.load(private / f'client-{name}.json')
                v.strict(client['case'], wire['case'])
                assert client['raw'] == wire['raw']
                assert re.fullmatch(r'HTTP/1\.[01] 200 OK', client['response_headers'][0])
            plan = v.load(root / f'store-plan-{lane}.json')
            prepared = v.load(private / 'fixture-result.json')
            assert prepared['committed'] and len(prepared['insert_records']) == 2
            for proposed, actual, row in zip(plan['rows'], prepared['insert_records'], prepared['after']['store']):
                assert actual == {'queryString': proposed['sql'], 'bindValue': proposed['bindValue'], 'rowCount': 1}
                assert set(row) == set(proposed['expected'])
                for field, value in proposed['expected'].items():
                    if field in {'store_id', 'logo_image_id', 'sort', 'is_recycle', 'version_type',
                                 'is_delete', 'create_time', 'update_time', 'group_id', 'status'}:
                        assert Decimal(str(row[field])) == Decimal(value)
                    else:
                        assert row[field] == value
            rows = {r['mac']: r for r in v.load(private / 'final-independent.json')['rows']}
            events = [json.loads(line, parse_float=Decimal) for line in (private / 'pdo-native.jsonl').read_text().splitlines()]
            for event in events:
                if event['layer'] != 'actual PDOStatement.execute' or event['operation'] != 'INSERT':
                    continue
                fields = v.parse_insert(event['queryString'], event['bindValue'])
                form = cases[event['scenario']]['form']
                row = rows[form['mac']]
                for field, bind in fields.items():
                    actual = bind['value']
                    physical = row['exact_stopped_at'] if field == 'stopped_at' else row[field]
                    if field in {'calories', 'fat_burn_efficiency'}:
                        assert Decimal(str(actual)) == Decimal(str(physical))
                        assert bind['php_type'] == 'double'
                    elif isinstance(actual, int):
                        assert actual == int(physical) and bind['php_type'] == 'integer'
                    else:
                        assert actual == physical and bind['php_type'] == 'string'
            cleanup = v.load(private / 'resource-cleanup.json')
            assert cleanup['own_worker_stopped'] and cleanup['own_port_closed']
            assert cleanup['own_tokens_removed'] == 2 and cleanup['own_cache_runtime_source_removed']
            assert cleanup['retained_marked_store_rows'] == 2 and cleanup['retained_formal_rope_rows'] == 4
            assert cleanup['business_DELETE'] == cleanup['DDL'] == 0 and cleanup['no_nonown_signal_sent']
    finally:
        sys.path.pop(0)
        sys.modules.pop('verify', None)
    run(BASE, sys.executable, '-m', 'unittest', 'test_verify.py')
    assert json.loads(run(BASE, sys.executable, 'seal.py', '--verify')) == seal

def targets():
    return [item('ai_api', method, '/api/RopeSkipping/' + action, BASE,
        evidence_only=True, risk='formal-owned-rope-upload-exact-unsigned-timestamp-and-complete-response-contract')
        for method, action in [('POST', 'add'), ('GET', 'latest'), ('GET', 'list')]]

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