<?php
declare(strict_types=1);
require __DIR__.'/common.php';$lane=getenv('SM7_LANE');$runtime=getenv('SM7_RUNTIME');$base=dirname($runtime);$approved=['/tmp/cdx-store-menu7-B-PDEqef','/tmp/cdx-store-menu7-C-Vy4WDq'];if(!in_array($base,$approved,true)||is_link($runtime)){exit(78);}
$port=$lane==='B'?18391:18392;if($s=@fsockopen('127.0.0.1',$port,$n,$e,1)){fclose($s);throw new RuntimeException('Stop owned HTTP before cleanup');}
$removed=0;$dir=$runtime.'/cache';if(is_dir($dir)){foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir,FilesystemIterator::SKIP_DOTS)) as $f){if($f->isFile()&&!$f->isLink()){if(!unlink($f->getPathname())){throw new RuntimeException('Private generated cache cleanup');}$removed++;}}}
$actor=smLoad('actor-private.json');$pre=smLoad('preflight-private.json');$db=smPdo();$own=smRows($db,'SELECT * FROM ydy_user WHERE id=? AND uuid=? AND account=? AND create_by=?',[$actor['id'],$actor['uuid'],$actor['marker'],$actor['marker']]);
$ownOk=count($own)===1&&smDigest($own)===smDigest([$actor['source']]);$natural=smUserDigest($db,$actor['id']);$naturalOk=$natural===$pre['natural_user_before'];$funds=count($own)===1&&bccomp((string)$own[0]['balance'],'0',2)===0&&bccomp((string)$own[0]['pay_money'],'0',2)===0;
$report=['lane'=>$lane,'independent_new_connection'=>true,'port_not_listening'=>true,'state_file_exists'=>is_file(__DIR__.'/worker_state.json'),'cache_files_remaining'=>0,'private_generated_cache_files_removed'=>$removed,'owned_actor_unchanged'=>$ownOk,'owned_actor_funds_zero'=>$funds,'owned_actor_retained'=>['id'=>$actor['id'],'uuid'=>$actor['uuid'],'marker'=>$actor['marker'],'type'=>0,'status'=>0],'natural_user_before'=>$pre['natural_user_before'],'natural_user_after_excluding_exact_owned_pk'=>$natural,'natural_user_unchanged'=>$naturalOk,'database_writes'=>0];
smSave('cleanup-report-private.json',$report);echo json_encode($report),PHP_EOL;exit(!$ownOk||!$funds||!$naturalOk||$report['state_file_exists']?1:0);
