<?php
declare(strict_types=1);
date_default_timezone_set('Asia/Shanghai');require __DIR__.'/common.php';
$db=smPdo();$lane=getenv('SM7_LANE');$root=getenv('SM7_ROOT');$runtime=getenv('SM7_RUNTIME');$base=getenv('SM7_BASE');$actor=smLoad('actor-private.json');$old=smLoad('responses-private.json');
if(hash_file('sha256',$root.'/application/p/logic/Equipment.php')!=='36b6016d6c4bd6a12bbe0bf2c0a483775303c5b22d1791dcb0fa6832b07738b9'){throw new RuntimeException('Approved Equipment SHA drift');}
$own=smRows($db,'SELECT * FROM ydy_user WHERE id=? AND uuid=? AND account=? AND create_by=?',[$actor['id'],$actor['uuid'],$actor['marker'],$actor['marker']]);if(count($own)!==1||smDigest($own)!==smDigest([$actor['source']])){throw new RuntimeException('Retained actor unchanged gate');}
$before=smDigest(smRows($db,'SELECT * FROM ydy_equipment_version'));require $root.'/application/base/Security.php';$token=\app\base\Security::encrypt(implode("\t",[(string)$actor['id'],$actor['uuid'],$actor['marker'],'0','','',$actor['marker']]));
$strict=static function($a,$b,string $p='$')use(&$strict):?string{if(gettype($a)!==gettype($b)){return $p.':type';}if(is_object($a)){$a=get_object_vars($a);$b=get_object_vars($b);ksort($a);ksort($b);}if(is_array($a)){if(array_keys($a)!==array_keys($b)){return $p.':keys';}foreach($a as $k=>$v){if(($err=$strict($v,$b[$k],$p.'.'.$k))!==null){return $err;}}return null;}return $a===$b?null:$p.':value';};
$format=static function(array $r)use($lane):array{if($lane==='C'&&isset($r['create_time'])&&is_string($r['create_time'])&&preg_match('/^((\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}))\.0{1,6}$/D',$r['create_time'],$m)&&(int)$m[2]>=1000&&checkdate((int)$m[3],(int)$m[4],(int)$m[2])&&(int)$m[5]<=23&&(int)$m[6]<=59&&(int)$m[7]<=59){$r['create_time']=$m[1];}return $r;};
$cases=[];$responses=[];$source=[];$error=null;
try{foreach(['VERSION_LIST','VERSION_READ','VERSION_PAGE2','VERSION_MISSING'] as $name){
    $oldCase=$old[$name];$p=$oldCase['params'];$opts=['method'=>'POST','header'=>"Host: cdx-store-menu7.invalid\r\nContent-Type: application/x-www-form-urlencoded;charset=UTF-8\r\ntoken: ".$token."\r\nX-Pilot-Scenario: PILOT_SM7_".$name."\r\n",'content'=>http_build_query($p),'ignore_errors'=>true,'follow_location'=>0,'timeout'=>25];
    $raw=file_get_contents($base.$oldCase['path'],false,stream_context_create(['http'=>$opts]));preg_match('~^HTTP/\S+ (\d+)~',$http_response_header[0]??'',$match);$status=(int)($match[1]??0);$body=json_decode((string)$raw,false,512,JSON_THROW_ON_ERROR);
    if(in_array($name,['VERSION_LIST','VERSION_PAGE2'],true)){$rows=smRows($db,smTop('SELECT * FROM ydy_equipment_version ORDER BY create_time DESC',10));$rows=array_slice($rows,($p['page']-1)*$p['pageSize'],$p['pageSize']);$rawRows=$rows;$exp=['row'=>array_map($format,$rows),'total'=>(int)$db->query('SELECT COUNT(*) FROM ydy_equipment_version')->fetchColumn()];}
    else{$rows=smRows($db,'SELECT * FROM ydy_equipment_version WHERE uuid=?',[$p['uuid']]);$rawRows=$rows;$exp=$rows?$format($rows[0]):null;}
    $expected=json_decode(json_encode($exp,JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR));$diff=$strict($expected,$body->data??null);$times=[];foreach($rawRows as $r){$times[]=['original_length'=>strlen($r['create_time']),'output_length'=>strlen($format($r)['create_time']),'valid_zero_fraction_source'=>preg_match('/\.0{1,6}$/D',$r['create_time'])===1];}
    $cases[]=['case'=>$name,'method'=>'POST','path'=>$oldCase['path'],'http_status'=>$status,'code'=>$body->code??null,'source_pass'=>$status===200&&($body->code??null)===0&&$diff===null,'difference'=>$diff,'rows'=>count($rawRows),'time_contract'=>$times];$responses[$name]=['method'=>'POST','path'=>$oldCase['path'],'http_status'=>$status,'body'=>$body,'wire_bytes'=>strlen((string)$raw),'wire_sha256'=>hash('sha256',(string)$raw)];$source[$name]=['raw_rows'=>$rawRows,'expected'=>$expected];
}}catch(Throwable $e){$error=['class'=>get_class($e),'message_sha256'=>hash('sha256',$e->getMessage())];smSave('version-final-error-private.json',['message'=>$e->getMessage()]);}
$after=smDigest(smRows($db,'SELECT * FROM ydy_equipment_version'));$events=[];foreach(file($runtime.'/queries.jsonl',FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES)?:[] as $line){$events[]=json_decode($line,true);}$report=['lane'=>$lane,'cases'=>$cases,'unexpected'=>$error,'before'=>$before,'after'=>$after,'version_natural_unchanged'=>$before===$after,'actor_unchanged'=>true,'new_actor_rows'=>0,'database_writes'=>0,'source_sha256'=>['application/p/logic/Equipment.php'=>hash_file('sha256',$root.'/application/p/logic/Equipment.php')],'events'=>$events];
smSave('version-final-report-private.json',$report);smSave('version-final-responses-private.json',$responses);smSave('version-final-source-private.json',$source);echo json_encode(['lane'=>$lane,'cases'=>$cases,'unexpected'=>$error!==null,'source_unchanged'=>$before===$after,'new_actor_rows'=>0]),PHP_EOL;exit($error||$before!==$after||array_filter($cases,static function($c){return !$c['source_pass'];})?1:0);
