<?php

declare(strict_types=1);

require dirname(__DIR__) . '/app/bootstrap.php';

use App\Core\Database;

$dryRunId=(int)($argv[1]??0);
$status=strtoupper(trim((string)($argv[2]??'')));
$before=(int)($argv[3]??0);
$after=(int)($argv[4]??0);
$actor=trim((string)($argv[5]??'DIAR_ENGINE'));
$result=['schema'=>'DIAR4A_DRY_RUN_RESULT_V1','status'=>'FAIL','dry_run_id'=>$dryRunId,'oracle_writes'=>'DIAR_CONTROL_TABLES_ONLY'];
try{
 if($dryRunId<=0||!in_array($status,['PASS','FAIL'],true)){throw new RuntimeException('USAGE: dry_run_id PASS|FAIL before_cases after_cases [actor]');}
 $row=Database::fetchOne('njch',"SELECT d.VERSION_ID version_id,v.CONFIG_HASH config_hash,d.STATUS_CODE status_code FROM DASH_DIAR_DRY_RUNS d JOIN DASH_DIAR_RULE_VERSIONS v ON v.VERSION_ID=d.VERSION_ID WHERE d.DRY_RUN_ID=:dry_run_id",['dry_run_id'=>$dryRunId]);
 if(!$row){throw new RuntimeException('DRY_RUN_NOT_FOUND');}
 if(!in_array((string)$row['status_code'],['PENDING','RUNNING'],true)){throw new RuntimeException('DRY_RUN_ALREADY_FINAL');}
 Database::executeTransaction('njch',[
  ['sql'=>"UPDATE DASH_DIAR_DRY_RUNS SET STATUS_CODE=:status_code,STARTED_AT=NVL(STARTED_AT,SYSDATE),COMPLETED_AT=SYSDATE,BEFORE_CASES=:before_cases,AFTER_CASES=:after_cases,DELTA_CASES=:delta_cases,RESULT_HASH=:result_hash,ERROR_MESSAGE=:error_message WHERE DRY_RUN_ID=:dry_run_id",'params'=>['status_code'=>$status,'before_cases'=>$before,'after_cases'=>$after,'delta_cases'=>$after-$before,'result_hash'=>(string)$row['config_hash'],'error_message'=>$status==='FAIL'?'Engine reported FAIL':null,'dry_run_id'=>$dryRunId]],
  ['sql'=>"INSERT INTO DASH_DIAR_AUDIT (AUDIT_ID,ACTOR_USERNAME,ACTION_CODE,TARGET_TYPE,TARGET_KEY,OLD_VALUE,NEW_VALUE,CREATED_AT) VALUES (DASH_DIAR_AUDIT_SEQ.NEXTVAL,:actor,'DRY_RUN_COMPLETED','DRY_RUN',:target_key,:old_value,:new_value,SYSDATE)",'params'=>['actor'=>substr($actor,0,128),'target_key'=>(string)$dryRunId,'old_value'=>(string)$row['status_code'],'new_value'=>$status]],
 ]);
 $result['status']='PASS';$result['dry_run_status']=$status;$result['configuration_hash']=(string)$row['config_hash'];$result['before_cases']=$before;$result['after_cases']=$after;$result['delta_cases']=$after-$before;
}catch(Throwable $e){$result['error']=preg_replace('/\s+/',' ',(string)$e->getMessage());}
echo json_encode($result,JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES),PHP_EOL;
exit($result['status']==='PASS'?0:1);
