<?php
declare(strict_types=1);require __DIR__.'/common.php';
$runtime=getenv('SM7_RUNTIME');$lane=getenv('SM7_LANE');$destination=__DIR__.'/private-evidence';
if(!preg_match('#^/tmp/cdx-device-catalog-[BC]-[A-Za-z0-9]+$#D',__DIR__)||is_dir($destination)||is_link($runtime)){throw new RuntimeException('Private export root/first-only guard');}
$files=['spec-private.json','after-private.json','report-private.json','boundary-private.json','prepared-private.json','queries.jsonl','native-stats-private.json','cleanup-private.json','source-mysql-metadata-private.json'];
foreach(['card-spec','card-after','card-report','green-spec','green-after','green-report','green-prepared','card-collection-tool-repair'] as $name){if(is_file($runtime.'/'.$name.'-private.json')){$files[]=$name.'-private.json';}}
foreach(glob($runtime.'/raw-*-private.json')?:[] as $file){$files[]=basename($file);}
mkdir($destination,0700);$manifest=[];
foreach($files as $name){if(!preg_match('/^[A-Za-z0-9._-]+$/D',$name)||is_link($runtime.'/'.$name)){throw new RuntimeException('Frozen evidence filename');}$content=file_get_contents($runtime.'/'.$name);if(strpos($name,'spec-')!==false||strpos($name,'after-')!==false){$data=json_decode($content,true,512,JSON_THROW_ON_ERROR);$scan=static function($value)use(&$scan):void{if(!is_array($value)){return;}if(isset($value['source_sets']['actor'])){foreach($value['source_sets']['actor'] as $actor){$keys=array_keys($actor);sort($keys);$safe=['account','full_row_digest','id','status','type','uuid'];sort($safe);if($keys!==$safe){throw new RuntimeException('Actor credential-column export rejected');}}}foreach($value as $child){$scan($child);}};$scan($data);}
 copy($runtime.'/'.$name,$destination.'/'.$name);chmod($destination.'/'.$name,0600);$manifest[$name]=['bytes'=>strlen($content),'sha256'=>hash('sha256',$content)];}
file_put_contents($destination.'/EVIDENCE_MANIFEST.json',json_encode($manifest,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));chmod($destination.'/EVIDENCE_MANIFEST.json',0600);
echo json_encode(['lane'=>$lane,'private_evidence_path'=>$destination,'files'=>count($manifest),'manifest_sha256'=>hash_file('sha256',$destination.'/EVIDENCE_MANIFEST.json'),'raw_wire_reencoded'=>false,'actor_credential_values_exported'=>false,'natural_pii_public_or_git'=>false]),PHP_EOL;
