<?php
require_once dirname(__DIR__, 2) . '/runtime/wr_bootstrap.php';
@set_time_limit(1200);
@ini_set('memory_limit', '1536M');
require_once dirname(__DIR__, 2) . '/config/config.php';
if (!wr_db_guard_normalize()) {
    wr_json_response(array('message' => 'DB connection unavailable'), 'V51', '51.8.0', 'ERROR', 500, '', false);
}
require_once dirname(__DIR__) . '/supreme/ChairmanSupremeDecisionEngineV51.php';
$date = '';
foreach (array('race_date', 'date', 'review_date') as $dateKey) {
    if (!isset($_GET[$dateKey])) {
        continue;
    }
    $candidate = trim((string)$_GET[$dateKey]);
    $dt = DateTimeImmutable::createFromFormat('!Y-m-d', $candidate);
    $errors = DateTimeImmutable::getLastErrors();
    if ($dt instanceof DateTimeImmutable
        && ($errors === false || ((int)$errors['warning_count'] === 0 && (int)$errors['error_count'] === 0))
        && $dt->format('Y-m-d') === $candidate) {
        $date = $candidate;
        break;
    }
}
if ($date === '') {
    $date = (new DateTimeImmutable('now', new DateTimeZone('Asia/Hong_Kong')))->format('Y-m-d');
}
$venue = isset($_GET['venue']) ? trim((string)$_GET['venue']) : '';
$venue = preg_replace('/[^A-Za-z0-9_\-]/', '', $venue);
$action = isset($_GET['action']) ? trim((string)$_GET['action']) : 'latest';
$engine = new ChairmanSupremeDecisionEngineV51($conn);
$result = $action === 'build' ? $engine->build($date, $venue) : $engine->latest($date, $venue);
$status = isset($result['status']) ? (string)$result['status'] : (empty($result) ? 'EMPTY' : 'OK');
$http = in_array($status, array('SOURCE_MISSING', 'ERROR'), true) ? 500 : 200;
wr_json_response($result, 'V51', '51.8.0', $status, $http, $date . '|' . $venue, !empty($result['races']));
