#!/usr/bin/env python3
"""Eight ledger/customer reads, one shared source failure, one explicit no-DB enum."""
import importlib.util
from pathlib import Path
import sys
import integrate_20261010 as tool
from integrate_20261011_batches40_42 import private_files, run, sha
from integrate_20261011_batches46_48 import item

BASE=tool.AI+'parallel-ai-ledger-feedback-read10-20261011/'
def verify():
    root=tool.ROOT/BASE
    assert sha(root/'MANIFEST.sha256')=='deb7ef1f5a1a37b86ddf1d8bedd77337b43bdcd2426eb4c900c4ceb9584c0f5f'
    m=tool.load(BASE+'manifest.json');assert len(m['public'])==77 and len(m['private'])==275
    for record in m['public']+m['private']:
        p=Path(record['path']);assert not p.is_absolute() and '..' not in p.parts
        f=root/p;assert f.is_file() and not f.is_symlink() and f.stat().st_size==record['bytes'] and sha(f)==record['sha256']
    assert all(r['path'].startswith('private-evidence/') for r in m['private'])
    private_files(root/'private-evidence',{r['path'][len('private-evidence/'):]:r for r in m['private']})
    sys.path.insert(0,str(root));modules={}
    try:
        for name in ['compare','verify_final','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['verify_final'].verify_all()
        assert r['true_HTTP']==r['complete_wire']==76 and r['B_raw_trace_only_equal']==r['strict_BC_pairs']==6
        assert r['final_full_original_scopes_unchanged'] and r['fixture_retained_each']==7
        assert sum(not c['pass'] for c in r['original']['B'])==0 and sum(not c['pass'] for c in r['original']['C'])==16
        assert len(r['final']['B'])==6 and len(r['final']['C'])==16 and all(c['pass'] for rows in r['final'].values() for c in rows)
        audit=modules['sql_audit'].all_audits()
        for phase,executed,business,failed in [('B-original',86,49,0),('C-original',106,19,14),('B-final',42,24,0),('C-final',122,38,0)]:
            a=audit[phase]['HTTP_only'];assert a['actual_executes']==executed and a['business_SELECT']==business and a['prepare_failures']==failed and a['DML_DDL']==0
        assert sum(audit[n]['all_preflight_auth_HTTP']['bind_plans'] for n in ['B-final','C-final'])==172
    finally:
        sys.path.pop(0)
        for name in ['compare','verify_final','sql_audit']:sys.modules.pop(name,None)
    run(BASE,sys.executable,'-m','unittest','test_compare.py','test_sql_audit.py')
    source=tool.load(BASE+'source-final-sha.json');assert len(source['files'])==6168 and len(source['accepted_changes'])==6
    for relative in source['accepted_changes']:
        assert sha(tool.ROOT.parent/'zhctproject/ai_api'/relative)==source['files'][relative],relative
    for lane in ['B','C']:
        c=tool.load(BASE+'resource-cleanup-'+lane+'.json')
        assert c['independent_final36_exact'] and c['retained7_full_rows_exact']==7 and c['final_source_pins_verified']==6168
        assert c['own_source_cache_runtime_removed'] and c['Auth_cache_files_before_cleanup']==0
        assert all(s['absent'] for s in c['original_and_final_workers_absent'].values())
        assert c['DML']==c['DDL']==c['HTTP']==0
    for record in m['public']+m['private']:assert sha(root/record['path'])==record['sha256']

def targets():
    paths=[f'/{side}/{module}/log' for side in ['store','terminal'] for module in ['market.Points','user.Balance']]
    paths += ['/store/user.UserFeedback/info','/store/user.UserFeedback/list','/store/User/list','/terminal/User/list']
    result=[item('ai_api','GET',p,BASE,
        risk='readonly-owned-zero-ledger-feedback-and-active-customer-no-account-mutation',
        parity='partial-native-SQL-full-DTO-row-values-types-and-B-six-original-raw-bodies-unchanged',
        boundary_empty_min_max='partial-page2-cross-date-scene-and-missing-ids-original-contract-no-fuzzy-feedback-or-nonzero-financial-HTTP') for p in paths]
    result.append(item('ai_api','GET','/store/dishes.Dishes/all',BASE,
        scope='shared-original-missing-Query-getAll-no-business-SQL',
        mysql_state='tested-fail-shared-original-undefined-method',dm_state='tested-fail-shared-original-undefined-method',
        success_case='tested-fail-shared-original-undefined-method-not-DM-regression',
        mysql_readback='not-applicable',dm_readback='not-applicable',
        parity='tested-pass-same-original-error-not-positive-business-result'))
    result.append(item('ai_api','GET','/terminal/recommend.Recommend/foodCategory',BASE,
        scope='no-db',readback='not-applicable',mysql_readback='not-applicable',dm_readback='not-applicable',
        success_case='tested-pass-complete-source-static-enum-only-no-business-DB',
        parity='tested-pass-source-complete-twelve-static-enum-values-not-database-coverage'))
    return result

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