<?php
@set_time_limit(1200);
@ini_set('memory_limit','1536M');

require_once dirname(__DIR__,2) . '/config/config.php';
if (!isset($conn) && isset($db)) $conn=$db;
if (!isset($conn) || !($conn instanceof mysqli)) die('DB connection not found');

require_once dirname(__DIR__) . '/explain/ChairmanExplainableAIEngineV48.php';

$date = isset($_GET['race_date']) ? trim($_GET['race_date']) :
    (isset($_GET['date']) ? trim($_GET['date']) :
    (isset($_GET['review_date']) ? trim($_GET['review_date']) : date('Y-m-d')));

$venue = isset($_GET['venue']) ? trim($_GET['venue']) : '';
$raceNum = isset($_GET['race_num']) ? intval($_GET['race_num']) : 0;
$action = isset($_GET['action']) ? $_GET['action'] : 'latest';

$engine = new ChairmanExplainableAIEngineV48($conn);
$result = $action === 'build'
    ? $engine->build($date,$venue,$raceNum)
    : $engine->latest($date,$venue,$raceNum);

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