#!/usr/bin/env python3
"""Verify sanitized S4 evidence; never reads private natural rows or secrets."""
import copy,json,pathlib,sys
HERE=pathlib.Path(__file__).resolve().parent

def validate(green,old,source):
    assert green['exit_code']==0 and green['stderr_bytes']==0
    r=green['report']
    assert r['status']=='pass' and r['stage']=='complete' and r['php']=='7.4.33'
    assert r['assertions']==148 and r['sample_rows']==5 and r['wide_above_2pow53_samples']==0
    assert r['truth_before_sha256']==r['truth_after_sha256']=='1ccbb73fea3839a12fa9a3b1f5f1a5e5cdb42f52ddc88eb3bd737fd239ac3b05'
    assert r['restored_sha256']=='fbca8c4492e8bcfc9ebb73da0803171a980286449fd5a97a5bf5ea96da476665'
    assert r['actual_prepares']==9 and len(r['actual_sql_sha256'])==9
    assert len(set(r['actual_sql_sha256']))==r['sql_registry_count']==4
    assert r['business_select_executions']==12 and r['reexecute_additional_business_selects']==1
    assert r['cursor_connection_clones']==1 and r['schema_provider_reads']==1
    assert r['file_cache_cold_hot_equal'] is True and r['orm_file_cache_cold_hot_equal'] is True and r['hot_additional_prepares']==0
    assert r['actual_model_json_equal'] is True
    assert r['orm_paths']==['select','find','value','column_keyed','cursor']
    assert r['api_authorization_tested'] is False and r['store_scope_mode']=='tool_no_auth_fixed_five_pk_only'
    assert r['global_p0_closed'] is False and r['http_increment']==r['dml']==r['ddl']==r['business_dml']==0
    assert r['ownership_store_count']==1 and r['metadata_equal'] is True
    assert r['source_gate']==source and source['status']=='pass' and source['metadata_same'] is True and source['columns']==16 and source['business_reads']==0
    assert r['current_source_manifest']['app/common/database/DmBuilder.php']=='58e1e79ce69881cc305c6fd33adec0e9a3d030ac15b4c00ae464cbaa4cce2b59'
    assert len(r['reflection'])==13
    for x in r['reflection'].values():
        assert x['path'].startswith('/tmp/cdx-s4-orm-20261011.Bg1UG3/app-root/')
        assert x['sha256']==r['current_source_manifest'][x['path'].split('/app-root/',1)[1]]
    identity=r['identity'];assert identity['core_soft']==0 and identity['extra_decimal_defined'] is False and identity['int_size']==8
    components=identity['components'].copy();components.pop('/www/server/php/74/bin/php')
    assert identity['mapped']==components
    assert r['target']['schema_matches'] is True and r['target']['owned_established_loopback_5238_sockets']>=1
    assert r['negative_boundaries']=={'aggregate':'rejected_no_prepare','float_getter':'precision_loss_still_open','invalidated_rowset':'rejected_no_visible_row','join':'rejected_no_prepare','raw':'rejected_no_prepare','star':'rejected_no_prepare','unknown_sql':'rejected_no_prepare','wrong_bind':'rejected_no_prepare'}
    assert old['exit_code']==1 and old['stderr_bytes']==0
    red=old['report'];assert red['status']=='expected_red' and red['stage']=='statement_foreach'
    assert red['row_count']==5 and red['expected_width']==5 and red['visible_width']==9
    assert red['reason']=='old_native_foreach_bypasses_recovery'
    assert red['global_p0_closed'] is False and red['dml']==red['ddl']==red['http_increment']==0

def main():
    green=json.loads((HERE/'green-final.json').read_text());old=json.loads((HERE/'old.json').read_text());source=json.loads((HERE/'source_gate.json').read_text())
    validate(green,old,source)
    mutations=[('sample_rows',6),('wide_above_2pow53_samples',1),('truth_after_sha256','bad'),('restored_sha256','bad'),('actual_prepares',8),('sql_registry_count',5),('business_select_executions',11),('cursor_connection_clones',0),('orm_file_cache_cold_hot_equal',False),('hot_additional_prepares',1),('api_authorization_tested',True),('global_p0_closed',True),('http_increment',1),('dml',1),('metadata_equal',False),('ownership_store_count',2)]
    for key,value in mutations:
        bad=copy.deepcopy(green);bad['report'][key]=value
        try:validate(bad,old,source)
        except AssertionError:continue
        raise AssertionError('Mutation escaped: '+key)
    print(json.dumps({'status':'pass','evidence_positive':1,'negative_mutations':len(mutations),'business_reads':0}))

if __name__=='__main__':main()
