<?php
if (!function_exists('wr_json_generated_at')) { function wr_json_generated_at(){ try{return (new DateTimeImmutable('now',new DateTimeZone('Asia/Hong_Kong')))->format('Y-m-d H:i:s');}catch(Throwable $e){return wr_timezone_fallback_timestamp();} } }
if (!function_exists('wr_json_response')) {
    function wr_json_response($payload,$engine,$engineVersion,$status='OK',$httpCode=200,$runKey='',$resultsUsed=null){
        wr_output_guard_clean_api_noise();
        if(!headers_sent()){ http_response_code((int)$httpCode); header('Content-Type: application/json; charset=utf-8'); header('X-WinRacing-Runtime: V50.3'); header('X-WinRacing-Request-Id: '.wr_runtime_request_id()); }
        if(!is_array($payload)) $payload=array('result'=>$payload);
        if($resultsUsed===null) $resultsUsed=!empty($payload);
        $meta=array('status'=>$status,'engine'=>$engine,'engine_version'=>$engineVersion,'request_id'=>wr_runtime_request_id(),'run_key'=>(string)$runKey,'generated_at'=>wr_json_generated_at(),'execution_ms'=>wr_runtime_execution_ms(),'memory_mb'=>wr_runtime_memory_mb(),'results_used'=>(bool)$resultsUsed,'data'=>$payload);
        /* Preserve legacy top-level keys for existing dashboards/AJAX clients. */
        $response=array_merge($payload,$meta);
        $json=json_encode($response,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT|JSON_PARTIAL_OUTPUT_ON_ERROR);
        if($json===false){ $json='{"status":"ERROR","message":"JSON encoding failed"}'; }
        echo $json; exit;
    }
}
