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

require_once dirname(__DIR__) . '/bootstrap/chairman_v44_migration_bootstrap.php';
require_once dirname(__DIR__) . '/production/ChairmanAutoProductionService.php';

$raceDate = 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;
$mode = isset($_GET['mode']) ? strtoupper(trim($_GET['mode'])) : 'BALANCED';
$force = isset($_GET['force']) && $_GET['force'] === '1';

$allowedModes = array('BALANCED','AGGRESSIVE','CONSERVATIVE','DEFENSIVE');
if (!in_array($mode, $allowedModes, true)) $mode = 'BALANCED';

header('Content-Type: application/json; charset=utf-8');

try {
    $service = new ChairmanAutoProductionService($conn, $V44Engine);
    echo json_encode(
        $service->ensure($raceDate, $venue, $raceNum, $mode, $force),
        JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT
    );
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(array(
        'status'=>'AUTO_PRODUCTION_ERROR',
        'built'=>false,
        'error'=>$e->getMessage(),
        'race_date'=>$raceDate,
        'time'=>date('c')
    ), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(array(
        'status'=>'AUTO_PRODUCTION_ERROR',
        'built'=>false,
        'error'=>$e->getMessage(),
        'race_date'=>$raceDate,
        'time'=>date('c')
    ), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
}
