<?php

declare(strict_types=1);
require dirname(__DIR__) . '/app/bootstrap.php';

$year=(int)($argv[1]??date('Y')); $compare=(int)($argv[2]??($year-1)); $samples=max(3,min(10,(int)($argv[3]??3)));
$coldLimit=(float)($argv[4]??6000); $warmLimit=(float)($argv[5]??3000);
$traceDir=dirname(__DIR__).'/storage/evidence/revenue-trace';
$outDir=dirname(__DIR__).'/storage/evidence/revenue-page-acceptance-'.date('Ymd_His'); @mkdir($outDir,0775,true);
$files=is_dir($traceDir)?glob($traceDir.'/REVENUE_END_TO_END_TRACE_*.json'):[]; usort($files,function($a,$b){return filemtime($b)<=>filemtime($a);});
$wanted=$year.'_vs_'.$compare; $rows=[];
foreach($files as $file){
 $j=json_decode((string)file_get_contents($file),true); if(!is_array($j))continue;
 $server=$j['server']??[]; $ctx=$server['context']??[]; if(($ctx['comparison']??'')!==$wanted)continue;
 $dur=$server['durations_ms']??[]; $nav=$j['navigation']??[];
 $rows[]=['file'=>basename($file),'request_id'=>$j['request_id']??'', 'captured_at'=>$j['captured_at']??'',
  'php_total_ms'=>(float)($dur['php_request_total']??0),'revenue_query_ms'=>(float)($dur['revenue_query']??0),
  'profit_loss_ms'=>(float)($dur['profit_loss_query']??0),'oracle_connection_ms'=>(float)($dur['oracle_connection']??0),
  'ttfb_ms'=>(float)($nav['request_wait_ttfb_ms']??0),'load_complete_ms'=>(float)($nav['load_complete_ms']??0)];
 if(count($rows)>=$samples)break;
}
$rows=array_reverse($rows); // chronological within selected latest set
$status='FAIL';$reasons=[];$cold=null;$warm=[];
if(count($rows)<$samples){$reasons[]='Need at least '.$samples.' browser traces for '.$wanted.'; found '.count($rows).'.';}
else{
 $cold=$rows[0]['load_complete_ms']; for($i=1;$i<count($rows);$i++)$warm[]=$rows[$i]['load_complete_ms'];
 $warmAvg=$warm?array_sum($warm)/count($warm):0;
 if($cold>$coldLimit)$reasons[]='Cold load '.round($cold,2).' ms exceeds '.$coldLimit.' ms.';
 if($warmAvg>$warmLimit)$reasons[]='Warm average '.round($warmAvg,2).' ms exceeds '.$warmLimit.' ms.';
 if(!$reasons)$status='PASS';
}
$summary=['schema'=>'DDB_REVENUE_PRODUCTION_PAGE_ACCEPTANCE_V1','comparison'=>$wanted,'sample_count'=>count($rows),
 'required_samples'=>$samples,'cold_limit_ms'=>$coldLimit,'warm_limit_ms'=>$warmLimit,'cold_load_ms'=>$cold,
 'warm_average_ms'=>isset($warmAvg)?round($warmAvg,2):null,'status'=>$status,'reasons'=>$reasons,'samples'=>$rows,
 'oracle_writes'=>'NONE','generated_at'=>date(DATE_ATOM)];
file_put_contents($outDir.'/REVENUE_PRODUCTION_PAGE_ACCEPTANCE.json',json_encode($summary,JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES));
$fh=fopen($outDir.'/REVENUE_PRODUCTION_PAGE_ACCEPTANCE.csv','wb');fputcsv($fh,['request_id','php_total_ms','revenue_query_ms','profit_loss_ms','oracle_connection_ms','ttfb_ms','load_complete_ms']);
foreach($rows as $r)fputcsv($fh,[$r['request_id'],$r['php_total_ms'],$r['revenue_query_ms'],$r['profit_loss_ms'],$r['oracle_connection_ms'],$r['ttfb_ms'],$r['load_complete_ms']]);fclose($fh);
echo json_encode($summary,JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES).PHP_EOL;echo "Evidence: $outDir".PHP_EOL;exit($status==='PASS'?0:4);
