<?php
require __DIR__.'/source.php';
$schemaDir=__DIR__.'/schema-api-evidence';$marker='CDXMATSC261011';
$schemaReads=0;$schemaQueries=[];
$sq=static function($sql,$args=[])use($q,&$schemaReads,&$schemaQueries){$schemaReads++;$schemaQueries[]=['SQL'=>$sql,'bindings'=>$args];return $q($sql,$args);};
$ssave=static function($name,$value)use($schemaDir){$encoded=json_encode($value,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_PRESERVE_ZERO_FRACTION);if($encoded===false)throw new RuntimeException('Evidence encoding');file_put_contents($schemaDir.'/'.$name,$encoded);chmod($schemaDir.'/'.$name,0600);};
$schemaSource=static function()use($sq,$p,$ref,$check){
 $state=[];foreach(['staff'=>['uuid',$ref['staff_uuid']],'user'=>['id',$ref['user_id']],'actor'=>['id',$ref['actor_id']]]as $key=>$where){$row=$sq('SELECT * FROM '.$p.($key==='actor'?'user':$key).' WHERE '.$where[0].'=?',[$where[1]]);$check(count($row)===1,'Reference unique');$state[$key.'_sha256']=hash('sha256',json_encode($row[0],JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));}
 foreach(['nutrition_category','material_category']as $table)$state[$table]=$sq('SELECT * FROM '.$p.$table.' ORDER BY ID');
 return $state;
};
$slease=static function()use($schemaDir){return json_decode(file_get_contents($schemaDir.'/lease.json'),true);};
$sguard=static function($state,$lease)use($schemaDir,$check,$marker){
 $base=json_decode(file_get_contents($schemaDir.'/baseline.json'),true);$ids=array_map('strval',array_column($lease,'id'));
 $old=array_values(array_filter($state['material_category'],static function($r)use($ids){return !in_array((string)$r['id'],$ids,true);}));
 $check($old===$base['material_category'],'All original Material exact after stripping only leased new PK');
 $check($state['nutrition_category']===$base['nutrition_category'],'All Nutrition exact');
 foreach(['staff','user','actor']as $key)$check($state[$key.'_sha256']===$base[$key.'_sha256'],'Identity full-row hash exact');
 foreach($state['material_category']as $row)if(in_array((string)$row['id'],$ids,true))$check(in_array($row['name'],[$marker.'-P1',$marker.'-P2',$marker.'-L',$marker.'-L-U'],true),'Exact own marker/name');
};
$sclock=static function()use($sq,$lane){return $sq($lane==='B'?'SELECT CURRENT_TIMESTAMP(0) AS T':"SELECT CAST(CURRENT_TIMESTAMP(0) AS DATETIME(0)) AS T FROM DUAL")[0]['t'];};
$sown=static function($state,$suffix)use($marker,$check){$rows=array_values(array_filter($state['material_category'],static function($r)use($marker,$suffix){return $r['name']===$marker.'-'.$suffix;}));$check(count($rows)===1,'Own row unique '.$suffix);return $rows[0];};
