<?php
@set_time_limit(60);

require_once dirname(__DIR__) . '/safety/ChairmanRuntimeLoggerV502.php';
ChairmanRuntimeLoggerV502::install('api_runtime_health_v50_2', true);

require_once dirname(__DIR__,2) . '/config/config.php';
if (!isset($conn) && isset($db)) $conn=$db;

require_once dirname(__DIR__) . '/safety/ChairmanSchemaCompatibilityGuardV501.php';

$result=array(
    'status'=>'OK',
    'framework'=>'WinRacing Chairman',
    'version'=>'V50.2 Header Safe',
    'run_id'=>ChairmanRuntimeLoggerV502::runId(),
    'generated_at'=>date('c'),
    'php_version'=>PHP_VERSION,
    'db'=>'ERROR',
    'buffer_level'=>ChairmanRuntimeLoggerV502::bufferLevel(),
    'headers'=>ChairmanRuntimeLoggerV502::headersSentInfo(),
    'cache'=>array(),
    'schema'=>array()
);

if (isset($conn) && $conn instanceof mysqli) {
    $result['db']=@$conn->ping()?'OK':'ERROR';
    $guard=new ChairmanSchemaCompatibilityGuardV501($conn);
    $result['schema']=$guard->inspect();
} else {
    $result['status']='ERROR';
    $result['schema']=array('status'=>'ERROR','issues'=>array('DB connection not found'));
}

$cacheDir=dirname(__DIR__) . '/cache';
$result['cache']=array(
    'dir'=>$cacheDir,
    'exists'=>is_dir($cacheDir),
    'writable'=>is_dir($cacheDir) && is_writable($cacheDir)
);

$result['execution_ms']=ChairmanRuntimeLoggerV502::executionMs();

if (!headers_sent()) {
    header('Content-Type: application/json; charset=utf-8');
    header('X-WinRacing-Version: V50.2-Header-Safe');
    header('X-WinRacing-Run-Id: '.ChairmanRuntimeLoggerV502::runId());
}

echo json_encode(
    $result,
    JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT
);
