<?php
declare(strict_types=1);require __DIR__.'/native.php';require __DIR__.'/observer.php';require $root.'/vendor/autoload.php';$app=new \think\App($root);$dir=$runtime.'/observer-test-cache/';$driver=new \think\cache\driver\File($app,['path'=>$dir]);$key='source_numeric_one';ck($driver->set($key,1,5),'Real original File.set');$file=$driver->getCacheKey($key);$raw=file_get_contents($file);$checks=1;$negatives=0;ck(numericRepeatBytes($raw)&&substr($raw,32)==='1','Real frozen source numeric format');$checks++;
foreach([substr($raw,0,32).'i:1;',substr($raw,0,32).'0',substr($raw,0,32).'2',str_replace('000000000005','000000000006',$raw),$raw.'x',null,1,[]] as $bad){ck(!numericRepeatBytes($bad),'Corrupt numeric cache rejected');$checks++;$negatives++;}
$order=[];$persisted=null;$sentBody=null;$error=null;$r=new class{function getCode(){return 200;}function getHeader(){return ['Content-Type'=>'application/json'];}function getContent(){return '{"status":200,"data":{"unchanged":"raw"}}';}};
preserveSendObserve($r,function($v)use(&$order,&$persisted){$order[]='save';$persisted=$v;},function()use(&$order,&$sentBody,$r){$order[]='send';$sentBody=$r->getContent();},function()use(&$order){$order[]='observe';throw new RuntimeException('Forced source format observer error');},function($v)use(&$order,&$error){$order[]='error';$error=$v;},1.0,2.0);
ck($order===['save','send','observe','error']&&$sentBody===$persisted['raw_response_body']&&$persisted['http_status']===200&&$error['original_response_sent']===true,'Postcommit observer cannot lose/replace original response');$checks++;
// Reproduce the old observation failure from the original source format, without DB/HTTP.
$oldCheck=static function($value){ck(substr($value,32)==='i:1;','Legacy wrong numeric serialization');};try{$oldCheck($raw);throw new LogicException('Legacy failure not reproduced');}catch(RuntimeException $e){$checks++;}
ck($driver->delete($key)&&!is_file($file),'Only exact temporary test cache cleaned');saveOnce('observer-tests.json',['checks'=>$checks,'counterexamples'=>$negatives,'legacy_wrong_serialization_reproduced'=>true,'order'=>$order,'source_File_SHA'=>hash_file('sha256',$root.'/vendor/topthink/framework/src/think/cache/driver/File.php'),'source_Driver_SHA'=>hash_file('sha256',$root.'/vendor/topthink/framework/src/think/cache/Driver.php'),'original_numeric_bytes_sha256'=>hash('sha256',$raw),'SQL'=>0,'HTTP'=>0]);echo json_encode(['checks'=>$checks,'counterexamples'=>$negatives,'SQL'=>0,'HTTP'=>0]),"\n";
