<?php

/**
 * CLI: one sepsis Emergency Management question (main SBA generator path).
 * Usage: php tools/test_sepsis_emergency_one.php
 */

require dirname(__DIR__) . '/app/config/config.php';
require dirname(__DIR__) . '/app/ai/prompt_generator.php';
require dirname(__DIR__) . '/app/ai/form_generator_retry.php';

$job = [
    'id' => 0,
    'specialty' => 'Acute Medicine',
    'condition_name' => 'Sepsis',
    'presentation' => 'Septic shock',
    'skill' => 'Emergency Management',
    'skills' => 'Emergency Management',
    '_job_skills' => 'Emergency Management',
    'learning_outcome' => '',
    'summative_formative' => 'Summative',
    'year_level' => 'MLA Final Year',
    'tutor_comments' => '',
    'num_questions' => 1,
    'questions_completed' => 0,
    '_batch_prior_questions' => [],
];

$job['_sepsis_emergency_scenario_plan'] = sbaSepsisResolveEmergencyScenarioPlanItem($job);
$prompt = buildQuestionPrompt($job);

echo 'Prompt length: ' . strlen($prompt) . PHP_EOL;
echo 'Has JSON OUTPUT: ' . (stripos($prompt, 'Return valid JSON ONLY') !== false ? 'yes' : 'no') . PHP_EOL;
echo 'Scenario slot: ' . ($job['_sepsis_emergency_scenario_plan']['slot'] ?? 'n/a') . PHP_EOL;

// Simulate retry bug path: retry prompt must be string with full instructions
$fakeWarnings = [[
    'code' => 'sepsis.emergency_batch_duplicate_scenario_category',
    'severity' => 'high',
    'message' => 'Duplicate scenario category',
]];
$retryPrompt = formGeneratorBuildRetryUserPrompt($prompt, $fakeWarnings, 'Emergency Management', [
    '_sepsis_emergency_scenario_plan' => $job['_sepsis_emergency_scenario_plan'],
]);
echo 'Retry prompt type: ' . gettype($retryPrompt) . ', length: ' . strlen((string) $retryPrompt) . PHP_EOL;
echo 'Retry has JSON OUTPUT: ' . (stripos((string) $retryPrompt, 'Return valid JSON ONLY') !== false ? 'yes' : 'no') . PHP_EOL;

echo 'Calling OpenAI...' . PHP_EOL;
$fetch = formGeneratorOpenAiChatJsonQuestion($prompt, 'cli_test', 0);
if (!$fetch['ok']) {
    fwrite(STDERR, 'FAIL: ' . $fetch['error'] . PHP_EOL);
    fwrite(STDERR, 'Raw: ' . substr($fetch['raw'], 0, 500) . PHP_EOL);
    exit(1);
}

echo 'OK: valid JSON keys: ' . implode(', ', array_keys($fetch['data'])) . PHP_EOL;
echo 'Title: ' . ($fetch['data']['title'] ?? '') . PHP_EOL;
echo 'Key: ' . ($fetch['data']['correct_answer'] ?? '') . PHP_EOL;
