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

require_once dirname(__DIR__) . '/safety/ChairmanRuntimeLoggerV501.php';
ChairmanRuntimeLoggerV501::install('api_runtime_health_v50_1');

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

$result=array(
    'status'=>'OK',
    'framework'=>'WinRacing Chairman',
    'version'=>'V50.1 Safety Foundation',
    'run_id'=>ChairmanRuntimeLoggerV501::runId(),
    'generated_at'=>date('c'),
    'php_version'=>PHP_VERSION,
    'db'=>'ERROR',
    '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']=ChairmanRuntimeLoggerV501::executionMs();

header('Content-Type: application/json; charset=utf-8');
echo json_encode($result,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);
