#!/usr/bin/env python3
"""Root-only, once-per-batch transitions after read-only sealed proof replay."""
import importlib.util
import json
from pathlib import Path
import sys
import integrate_20261010 as tool
from integrate_20261011_batches40_42 import manifest, private_files, run, sha
from integrate_20261011_batches46_48 import item

WIDE = 'work/2026-09-28-smart-canteen-dm8-poc/store-gift-wide-http-20261011/'
DASH = tool.AI + 'parallel-ai-dashboard-export-read8-20261011/'

def module(base, name):
    spec = importlib.util.spec_from_file_location(name, tool.ROOT/base/(name+'.py'))
    result = importlib.util.module_from_spec(spec)
    sys.modules[name] = result
    spec.loader.exec_module(result)
    return result

def verify_wide():
    m = tool.load(WIDE+'FINAL_EXECUTION_MANIFEST.json')
    assert m['HTTP'] == 6 and m['preparation_INSERT'] == 10
    assert m['API_write'] == m['UPDATE'] == m['DELETE'] == m['DDL'] == 0
    assert len(m['public_files']) == 17 and len(m['private_files']) == 72
    assert not (tool.ROOT/WIDE/'private-evidence').is_symlink()
    for group in ['public_files', 'private_files']:
        for record in m[group]:
            path = tool.ROOT/WIDE/record['path']
            assert not path.is_symlink() and path.is_file()
            assert sha(path) == record['sha256'] and path.stat().st_size == record['bytes']
            assert oct(path.stat().st_mode & 0o777) == record['mode']
    for phase in ['red', 'green']:
        result = json.loads(run(WIDE, sys.executable, 'verify.py', '--phase', phase))
        assert result['HTTP_replayed'] == result['DB_access'] == 0
    run(WIDE, sys.executable, '-m', 'unittest', 'discover', '-p', 'test_verify.py')
    for lane in ['B', 'C']:
        clean = tool.load(WIDE+'cleanup.json')[lane]
        assert clean['port_closed'] and clean['own_runtime_source_config_cache_removed']
        assert clean['Auth_runner_removed'] and clean['retained_gift_rows'] == 5
        assert clean['original_parent_'+('10001' if lane == 'B' else '112175')+'_alive']
    for relative, digest in {
        'application/common/service/account/GiftFlowRead.php': 'f57365b16644086735a461eb09c8ad0a5cedddb3ae84047118191ef1cf7d8cb9',
        'application/p/logic/AccountSetting.php': '3ea41ffec4f328801d31a4e50a994df8e1f1dc5dfcb1464503a707f7ee06bf92',
        'application/p/logic/WalletFlow.php': '608042cee67e4d2ba4ddf64575fd6aae97db1da2b288c33e66caa831d4faaa9b',
    }.items():
        assert sha(tool.ROOT.parent/'zhctproject/store'/relative) == digest, relative

def verify_dashboard():
    m = tool.load(DASH+'manifest.json')
    manifest(DASH, m['files'])
    sys.path.insert(0, str(tool.ROOT/DASH))
    try:
        comparison = module(DASH, 'compare').verify()
        assert comparison['HTTP'] == 22 and comparison['full_source_DTO_passes'] == 18
        assert len(comparison['complete_BC_positive_pairs']) == 8
        assert len(comparison['historical_C_SQL_reds']) == len(comparison['historical_C_SUM_type_reds']) == 2
        assert len(comparison['MySQL_final_body_unchanged']) == 2
        sql = module(DASH, 'sql_audit').audit()
        assert sql == m['SQL']
    finally:
        sys.path.pop(0)
        for name in ['compare', 'sql_audit']:
            sys.modules.pop(name, None)
    run(DASH, sys.executable, '-m', 'unittest', 'discover', '-p', 'test_compare.py')
    for lane in ['B', 'C']:
        private_files(tool.ROOT/DASH/'private-evidence'/lane, m['raw'][lane])
        counts = sql[lane]['counts']
        assert counts['preparation_INSERT'] == 6
        assert counts['HTTP_DML'] == counts['DDL'] == counts['preparation_UPDATE'] == counts['preparation_DELETE'] == 0
        clean = m['cleanup'][lane]
        for key in ['port_closed', 'pid_gone', 'source_removed', 'private_cache_cli_header_native_removed',
                    'evidence_0600', 'evidence_dir_0700', 'preserved_master_original18102']:
            assert clean[key], (lane, key)
        assert clean['cache_files_before_cleanup'] == 0
    for relative, digest in m['business_fix_files'].items():
        assert sha(tool.ROOT.parent/'zhctproject/ai_api'/relative) == digest, relative
    assert m['interfaces'] == m['complete_BC_positive_pairs'] == 8 and m['native_assertions'] == 88
    manifest(DASH, m['files'])

def batches():
    wide = [item('store', 'POST', path, WIDE,
        risk='bounded-gift-ledger-read-no-money-mutation',
        boundary_empty_min_max='partial-five-unsigned-boundaries-exact-before-PDO-original-internal-int-contract-date-filter-unverified',
        **({'evidence_only': True} if path.endswith('giftFlowList') else {}))
        for path in ['/p/accountSetting/giftFlowList', '/p/walletFlow/list']]
    dashboard = [item('ai_api', 'GET', '/'+app+'/'+path, DASH,
        risk='readonly-statistics-synthetic-zero-money-own-preparation',
        boundary_empty_min_max='partial-nonempty-count-goods-rank-export-metadata-only-no-active-user-rank-nonzero-sale-or-file-generation')
        for app in ['store', 'terminal']
        for path in ['Home/data', 'statistics.Data/data', 'statistics.Data/survey', 'order.Export/list']]
    return [(54, wide, verify_wide), (55, dashboard, verify_dashboard)]

if __name__ == '__main__':
    for number, _, verify in batches():
        assert not Path(__file__).with_name(f'integration-20261011-batch{number}.json').exists(), 'Preserve original transition audit'
        verify()
    for number, targets, verify in batches():
        tool.main(targets, Path(__file__).with_name(f'integration-20261011-batch{number}.json'), verify)
