#!/usr/bin/env python3
"""Root pure offline replay of goods/Printer business reads and writes."""
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

BASE = tool.AI+'parallel-ai-goods-printer-read8-20261011/'

def verify():
    m = tool.load(BASE+'manifest.json')
    manifest(BASE, m['artifacts'])
    root = tool.ROOT/BASE
    # Import callables rather than __main__: never rewrite sealed derived JSON.
    sys.path.insert(0, str(root))
    try:
        modules = {}
        for name in ['compare', 'sql_audit']:
            spec = importlib.util.spec_from_file_location(name, root/(name+'.py'))
            module = importlib.util.module_from_spec(spec)
            sys.modules[name] = module
            spec.loader.exec_module(module)
            modules[name] = module
        r = modules['compare'].verify()
        assert r['HTTP'] == 40 and r['positive_full_original_projections_including_empty_boundary'] == 30
        assert len(r['full_BC_pairs']) == 18 and len(r['tool_cache_race_reds']) == 4 and r['business_reds'] == 0
        s = modules['sql_audit'].audit()
        assert s == m['sql']
        assert s['B']['HTTP'] == 22 and s['C']['HTTP'] == 18
        for lane in ['B', 'C']:
            assert s[lane]['INSERT'] == 2 and s[lane]['UPDATE'] == 4
            assert s[lane]['DELETE'] == s[lane]['DDL'] == s[lane]['read_phase_DML'] == 0
            assert s[lane]['preparation_INSERT'] == 2 and s[lane]['preparation_UPDATE'] == (2 if lane == 'B' else 1)
    finally:
        sys.path.pop(0)
        for name in ['compare', 'sql_audit']:sys.modules.pop(name, None)
    run(BASE, sys.executable, '-m', 'unittest', 'discover', '-p', 'test_compare.py')
    for lane in ['B', 'C']:
        private_files(root/'private-evidence'/lane, m['raw'][lane])
        c = tool.load(BASE+'resource-cleanup-'+lane+'.json')
        assert c['port_closed'] and c['pid_gone'] and c['source_removed']
        assert c['private_cache_cli_header_native_removed'] and c['cache_files_before_cleanup'] == 0
        assert c['evidence_0600'] and c['evidence_dir_0700'] and c['preserved_master_original18102']
    for relative, digest in m['actual_source_sha256'].items():
        assert sha(tool.ROOT.parent/'zhctproject/ai_api'/relative) == digest, relative
    assert m['interfaces'] == 14 and m['positive_key_successes'] == 28 and m['native_assertions'] == 160
    assert m['native_tool_race_red_assertions'] == 4 and m['business_source_changes'] == 0
    manifest(BASE, m['artifacts'])

def targets():
    result = [item('ai_api', 'GET', '/terminal/Goods/'+action, BASE,
        boundary_empty_min_max='partial-evidence-single-zero-stock-offline-owned-product-real-images-SKU-JSON-weight-and-tenant-missing-see-report')
        for action in ['list', 'listByIds', 'detail', 'basic']]
    for app in ['store', 'terminal']:
        for action in ['list', 'all', 'add', 'edit', 'delete']:
            result.append(item('ai_api', 'GET' if action in ['list', 'all'] else 'POST',
                f'/{app}/setting.Printer/{action}', BASE,
                risk='owned-configuration-CRUD-no-real-printer-or-SDK',
                boundary_empty_min_max='partial-evidence-synthetic-non-device-config-add-read-edit-softdelete-full-original-rows-no-default-settings-change',
                parity='partial-evidence-complete-wire-with-only-original-validated-own-ID-and-automatic-time-mapping'))
    return result

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