#!/usr/bin/env python3
"""Five bounded AI equipment/dish reads; real-device paths remain outside proof."""
import importlib.util
from pathlib import Path
import re
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-admin-device-dishes-read5-20261011/'
def verify():
    root=tool.ROOT/BASE
    records={}
    for line in (root/'MANIFEST.sha256').read_text().splitlines():
        digest,name=line.split('  ',1);p=Path(name)
        assert re.fullmatch('[0-9a-f]{64}',digest) and not p.is_absolute() and '..' not in p.parts
        assert name not in records
        records[name]=digest
    assert len(records)==77
    manifest(BASE,records);m=tool.load(BASE+'manifest.json')
    sys.path.insert(0,str(root));modules={}
    try:
        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
        old=modules['compare'].verify_original()
        assert old['HTTP']==16 and old['full_DTO_passes']==14 and len(old['original_C_datetime_reds'])==2
        result=modules['compare'].verify()
        assert result['HTTP']==20 and result['native_assertions']==80 and result['full_source_DTO_passes']==18
        assert result['effective_scenarios_all_green']==16 and result['whole_final_BC_pairs']==6
        assert len(result['B_complete_original_body_unchanged'])==len(result['C_required_failed_branch_retest_green'])==2
        sql=modules['sql_audit'].audit();assert sql==m['SQL']
    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,count in [('B',11),('C',16)]:
        assert len(m['raw'][lane])==count
        private_files(root/'private-evidence'/lane,m['raw'][lane])
        for name,r in m['raw'][lane].items():assert (root/'private-evidence'/lane/name).stat().st_size==r['bytes']
        c=sql[lane]['counts']
        assert c['HTTP']==10 and c['preparation_INSERT']==3 and c['business_SELECT']==16
        assert c['HTTP_DML']==c['HTTP_DDL']==c['preparation_UPDATE']==c['preparation_DELETE']==0
        assert sql[lane]['natural_device_credentials_consumed']==0
        clean=m['cleanup'][lane]
        for key in ['port_closed','pid_gone','source_removed','contract_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
    ddl=m['approved_C_schema_DDL']
    assert (ddl['business_DDL'],ddl['temporary_DDL'],ddl['business_DML'])==(1,3,0)
    assert ddl['temporary_rows_rollback0'] and ddl['old12_columns_indexes_constraints_triggers_exact'] and ddl['independent_new_PDO_readback']
    assert sha(root/'equipment-status-add.sql')==ddl['SQL_sha256']=='f9439485eafc2c54acc59114d58c8aa1fe9c5dff825e179b0364070a9d6ef508'
    assert len(m['final_actual_source'])==30
    for relative,digest in m['final_actual_source'].items():assert sha(tool.ROOT.parent/'zhctproject/ai_api'/relative)==digest,relative
    assert [n for n in m['original_source'] if m['original_source'][n]!=m['final_actual_source'][n]]==['app/admin/service/store/Equipment.php']
    manifest(BASE,records)

def targets():
    return [item('ai_api','GET',path,BASE,
        risk='bounded-inactive-device-metadata-and-dish-image-no-pairing-or-SDK',
        parity='partial-full-own-positive-and-boundary-BC-body-independent-natural-Store-category-oracle-valid-zero-date-contract',
        boundary_empty_min_max='partial-id0-type50-empty-and-missing-dish-fixed-error-no-device-write-or-pairing-proof')
        for path in ['/admin/store.Equipment/detail','/admin/store.Equipment/lists','/admin/store.Equipment/getStoreList','/terminal/dishes.Img/all','/terminal/recommend.Recommend/dishesCategory']]

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