<?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'), 'V52', '52.9.0', 'ERROR', 500, '', false);
}
require_once dirname(__DIR__) . '/learning/ChairmanSelfLearningEngineV52.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';
$engine = new ChairmanSelfLearningEngineV52($conn);
$result = $action === 'build' ? $engine->build($date,$venue) : $engine->latest($date,$venue);
$status = isset($result['status']) ? (string)$result['status'] : 'EMPTY';
$http = in_array($status,array('SOURCE_MISSING','ERROR'),true) ? 500 : 200;
wr_json_response($result,'V52','52.9.0',$status,$http,$date.'|'.$venue,!empty($result['feedback']));
