<?php
require_once dirname(__DIR__) . '/app/bootstrap.php';
$dir=storage_path('evidence/revenue-trace');
$latest=$dir.'/LATEST.json';
if(!is_file($latest)){fwrite(STDERR,"No browser trace found. Open revenue page once, wait for full load, then rerun.\n");exit(2);} 
$meta=json_decode((string)file_get_contents($latest),true); $file=$dir.'/'.($meta['file']??'');
if(!is_file($file)){fwrite(STDERR,"Latest trace file missing.\n");exit(3);} $d=json_decode((string)file_get_contents($file),true);
$n=$d['navigation']??[]; $s=$d['server']['durations_ms']??[];
$out=['status'=>'COMPLETE','request_id'=>$d['request_id']??'', 'server_ms'=>$s,'browser_navigation_ms'=>$n,'resource_count'=>$d['resources']['count']??0,'slowest_resources'=>array_slice($d['resources']['slowest']??[],0,10),'charts'=>$d['charts']??[],'source_file'=>$file];
$target=$dir.'/REVENUE_END_TO_END_SUMMARY_'.($d['request_id']??date('Ymd_His')).'.json'; file_put_contents($target,json_encode($out,JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES));
echo json_encode($out,JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES).PHP_EOL; echo "SUMMARY_FILE=$target\n";
