<?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'), 'V60', '60.0.0', 'ERROR', 500, '', false);
}
require_once dirname(__DIR__) . '/memory/ChairmanPatternMemoryEngineV53.php';
require_once dirname(__DIR__) . '/runtime/wr_chairman_os_scheduler_v60_0.php';

$date = '';
foreach (array('race_date', 'date', 'review_date') as $key) {
    if (!isset($_GET[$key])) { continue; }
    $candidate = trim((string)$_GET[$key]);
    $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']) ? preg_replace('/[^A-Za-z0-9_\-]/', '', trim((string)$_GET['venue'])) : '';
$action = isset($_GET['action']) ? trim((string)$_GET['action']) : 'latest';

$sourceEngine = new ChairmanPatternMemoryEngineV53($conn);
$source = $action === 'build' ? $sourceEngine->build($date, $venue) : $sourceEngine->latest($date, $venue);
$os = new ChairmanOSSchedulerV60();
$result = $os->build(is_array($source) ? $source : array(), $date, $venue);
$result['source_v53_status'] = isset($source['status']) ? $source['status'] : 'EMPTY';
$result['source_v53_version'] = isset($source['engine_version']) ? $source['engine_version'] : '54.9.0';
$result['source_data'] = $source;
wr_json_response($result, 'V60', '60.0.0', 'OK', 200, $date . '|' . $venue, true);
