<?php

require dirname(__DIR__) . '/validators/style_validator.php';
require dirname(__DIR__) . '/prompts/sba_sepsis_batch_concepts.php';
require dirname(__DIR__) . '/prompts/sba_ai_reviewer_prompt.php';
require dirname(__DIR__) . '/app/config/config.php';
require dirname(__DIR__) . '/app/ai/form_generator_retry.php';

function testWarnings(array $question, string $label): void
{
    $codes = [];
    foreach (validateSbaStyle($question) as $w) {
        if (is_array($w) && !empty($w['code'])) {
            $codes[] = (string) $w['code'];
        }
    }
    echo '=== ' . $label . ' ===' . PHP_EOL;
    echo 'Codes: ' . (count($codes) ? implode(', ', $codes) : '(none)') . PHP_EOL;
    $bad = [
        'sepsis.emergency_incomplete_key_without_narrow_lead_in',
        'sepsis.emergency_hypoxic_oxygen_unfair',
        'sepsis.emergency_batch_duplicate_resuscitation',
        'sepsis.emergency_lead_in_scenario_mismatch',
    ];
    foreach ($bad as $b) {
        if (in_array($b, $codes, true)) {
            echo 'UNEXPECTED: ' . $b . PHP_EOL;
        }
    }
    echo PHP_EOL;
}

$base = [
    '_current_skill' => 'Emergency Management',
    '_condition_name' => 'Sepsis',
    'specialty' => 'Acute Medicine',
    'presentation' => 'Septic shock',
    'skill' => 'Emergency Management',
    'lead_in' => 'What is the most appropriate immediate management?',
];

echo 'Hypoxia 96%: ' . (sbaSepsisStemHasClinicallySignificantHypoxia(
    'oxygen saturation 96% on breathing air'
) ? 'YES (bad)' : 'no (good)') . PHP_EOL;

echo 'Hypoxia 86%: ' . (sbaSepsisStemHasClinicallySignificantHypoxia(
    'oxygen saturation 86% on breathing air'
) ? 'yes (good)' : 'NO (bad)') . PHP_EOL;

echo 'Slot initial (96%, no treatment, persistent wording): '
    . sbaSepsisInferEmergencyScenarioCategory(
        'Persistent hypotension. No IV fluids or antibiotics have been administered yet. Oxygen saturation 96% on breathing air.',
        'What is the most appropriate immediate management?',
        'Start IV fluids and broad-spectrum IV antibiotics'
    ) . PHP_EOL;

echo 'Slot refractory (after fluids+abx): '
    . sbaSepsisInferEmergencyScenarioCategory(
        'IV fluids and broad-spectrum IV antibiotics have already been given. Persistent hypotension remains.',
        'What is the most appropriate next circulatory support step?',
        'Start noradrenaline infusion'
    ) . PHP_EOL;

echo 'Slot hypoxic (86%): '
    . sbaSepsisInferEmergencyScenarioCategory(
        'Oxygen saturation 86% on breathing air with hypotension.',
        'What is the most appropriate immediate management?',
        'Give oxygen, start IV fluids and broad-spectrum IV antibiotics'
    ) . PHP_EOL;

echo 'Key detect Initiate fluids+abx: ' . (sbaSepsisEmergencyKeyIncludesIvFluidsAndBroadSpectrumAntibiotics(
    'Initiate IV fluids and broad-spectrum IV antibiotics'
) ? 'yes (good)' : 'NO (bad)') . PHP_EOL;

echo 'Key detect Give intravenous fluids+abx: ' . (sbaSepsisEmergencyKeyIncludesIvFluidsAndBroadSpectrumAntibiotics(
    'Give intravenous fluids and broad-spectrum intravenous antibiotics'
) ? 'yes (good)' : 'NO (bad)') . PHP_EOL . PHP_EOL;

testWarnings(array_merge($base, [
    'title' => 'Initial septic shock resuscitation',
    'stem' => 'A 68 year old man with type 2 diabetes attends the emergency department with persistent hypotension. No IV fluids or antibiotics have been administered yet. His temperature is 39.1°C, pulse 118/min, blood pressure 82/48 mmHg, respiratory rate 24/min and oxygen saturation 96% on breathing air.',
    'option_a' => 'Start IV fluids and broad-spectrum IV antibiotics',
    'option_b' => 'Start vasopressors before adequate fluid resuscitation',
    'option_c' => 'Give oral antibiotics and observe',
    'option_d' => 'Arrange critical care review without starting treatment',
    'option_e' => 'Repeat lactate before treating persistent hypotension',
    'correct_answer_letter' => 'A',
    'correct_answer' => 'Start IV fluids and broad-spectrum IV antibiotics',
    'justification' => 'Combined resuscitation is required for septic shock with hypotension before other steps.',
]), 'Case 1: SpO2 96%, persistent hypotension, no fluids/abx yet');

testWarnings(array_merge($base, [
    'title' => 'Persistent hypotension in septic shock',
    'lead_in' => 'What is the most appropriate next circulatory support step?',
    'stem' => 'A 72 year old woman with urosepsis received adequate IV fluid resuscitation and broad-spectrum IV antibiotics have already been given. Persistent hypotension remains with blood pressure 78/42 mmHg.',
    'option_a' => 'Start noradrenaline infusion',
    'option_b' => 'Give a further fluid bolus without reassessing responsiveness',
    'option_c' => 'Broaden antibiotics without addressing shock',
    'option_d' => 'Ward review tomorrow if blood pressure improves',
    'option_e' => 'Repeat lactate before any vasopressor',
    'correct_answer_letter' => 'A',
    'correct_answer' => 'Start noradrenaline infusion',
    'justification' => 'Fluid-refractory septic shock after initial resuscitation requires vasopressor support.',
]), 'Case 2: persistent hypotension after fluids and antibiotics');

testWarnings(array_merge($base, [
    'title' => 'Hypoxic septic shock',
    'stem' => 'A 70 year old man is breathless in the emergency department. His temperature is 38.9°C, pulse 124/min, blood pressure 78/46 mmHg, respiratory rate 28/min and oxygen saturation 86% on breathing air.',
    'option_a' => 'Give oxygen, start IV fluids and broad-spectrum IV antibiotics',
    'option_b' => 'Start IV fluids and broad-spectrum IV antibiotics without oxygen',
    'option_c' => 'Give oxygen therapy only',
    'option_d' => 'Begin vasopressors before fluid resuscitation',
    'option_e' => 'Monitor observations without immediate treatment',
    'correct_answer_letter' => 'A',
    'correct_answer' => 'Give oxygen, start IV fluids and broad-spectrum IV antibiotics',
    'justification' => 'Hypoxic septic shock requires oxygen plus immediate sepsis resuscitation.',
]), 'Case 3: hypoxic SpO2 86% + oxygen/fluids/abx');

$prompt = buildSbaAiReviewerPrompt(array_merge($base, [
    'title' => 'Initial septic shock resuscitation',
    'stem' => 'A 68 year old man attends the emergency department. Oxygen saturation 96% on breathing air. No IV fluids or antibiotics have been administered yet.',
    'option_a' => 'Initiate IV fluids and broad-spectrum IV antibiotics',
    'option_b' => 'Start vasopressors before adequate fluid resuscitation',
    'option_c' => 'Give oral antibiotics and observe',
    'option_d' => 'Arrange critical care review without starting treatment',
    'option_e' => 'Repeat lactate before treating persistent hypotension',
    'correct_answer' => 'Initiate IV fluids and broad-spectrum IV antibiotics',
    'correct_answer_letter' => 'A',
    'justification' => 'Combined IV fluid resuscitation and broad-spectrum IV antibiotics are required for hypotensive septic shock.',
]), [[
    'code' => 'sepsis.emergency_incomplete_key_without_narrow_lead_in',
    'severity' => 'high',
    'message' => 'False test warning for scepticism check',
]], []);

echo 'Reviewer independent-first: ' . (stripos($prompt, 'Step 1 — Independent review') !== false
    && stripos($prompt, 'Step 1 — Independent review') < stripos($prompt, 'Rule-based style warnings') ? 'yes' : 'no') . PHP_EOL;
echo 'Reviewer not summariser: ' . (stripos($prompt, 'not a rule-warning summariser') !== false ? 'yes' : 'no') . PHP_EOL;
