<?php

/**
 * Run AI reviewer on four sepsis emergency tutor-review scenarios.
 * Usage: php tools/test_ai_reviewer_scenarios.php
 */

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

$base = [
    'specialty' => 'Acute Medicine',
    'condition_name' => 'Sepsis',
    'presentation' => 'Septic shock',
    'skill' => 'Emergency Management',
    '_current_skill' => 'Emergency Management',
    'year_level' => 'MLA Final Year',
    'summative_formative' => 'Summative',
    'tutor_comments' => '',
];

$scenarios = [
    '1_initial_septic_shock_spo2_96' => [
        'title' => 'Initial septic shock resuscitation',
        'stem' => 'A 68 year old man attends the emergency department with fever and confusion. His temperature is 39.2°C, pulse 118/min, blood pressure 82/48 mmHg, respiratory rate 22/min and oxygen saturation 96% on breathing air. No IV fluids or antibiotics have been given.',
        'lead_in' => 'What is the most appropriate immediate management?',
        'option_a' => 'Initiate IV fluids and broad-spectrum IV antibiotics',
        'option_b' => 'Start vasopressors before 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' => 'Initiate IV fluids and broad-spectrum IV antibiotics',
        'justification' => 'Untreated septic shock requires immediate IV fluid resuscitation and broad-spectrum IV antibiotics.',
        'style_warnings' => [],
    ],
    '2_persistent_hypotension_noradrenaline' => [
        'title' => 'Persistent hypotension in septic shock',
        'stem' => 'A 65 year old woman received adequate IV fluid resuscitation and broad-spectrum IV antibiotics 2 hours ago for septic shock. Her temperature is 38.4°C, pulse 118/min, blood pressure 78/42 mmHg, respiratory rate 24/min and oxygen saturation 95% on breathing air.',
        'lead_in' => 'What is the most appropriate next circulatory support step?',
        'option_a' => 'Start noradrenaline infusion with urgent critical care review',
        'option_b' => 'Give a further 500 mL fluid bolus without reassessing responsiveness',
        'option_c' => 'Repeat IV fluids and broad-spectrum IV antibiotics',
        'option_d' => 'Broaden antibiotics without addressing shock',
        'option_e' => 'Monitor observations on the ward without escalation',
        'correct_answer_letter' => 'A',
        'correct_answer' => 'Start noradrenaline infusion with urgent critical care review',
        'justification' => 'Fluid-refractory septic shock after initial resuscitation requires vasopressor support and critical care escalation.',
        'style_warnings' => [],
    ],
    '3_hypoxic_septic_shock' => [
        'title' => 'Hypoxic septic shock',
        'stem' => 'A 72 year old man is breathless in the emergency department. His temperature is 38.9°C, pulse 126/min, blood pressure 76/44 mmHg, respiratory rate 30/min and oxygen saturation 88% on breathing air. No treatment has been given.',
        'lead_in' => 'What is the most appropriate immediate management?',
        '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.',
        'style_warnings' => [],
    ],
    '4_abdominal_source_control' => [
        'title' => 'Abdominal source control in sepsis',
        'stem' => 'A 58 year old woman is 4 days after bowel surgery. She has received IV fluids and broad-spectrum IV antibiotics for sepsis. She remains febrile with temperature 38.7°C, pulse 110/min, blood pressure 96/55 mmHg, respiratory rate 20/min and oxygen saturation 95% on breathing air. She has worsening abdominal pain and peritonism with a tender distended abdomen.',
        'lead_in' => 'In addition to sepsis resuscitation, what is the most important next step?',
        'option_a' => 'Urgent surgical review for source control',
        'option_b' => 'Request an abdominal CT scan and await results',
        'option_c' => 'Broaden antibiotics without addressing the abdominal source',
        'option_d' => 'Repeat lactate measurement before further action',
        'option_e' => 'Continue current treatment without escalation',
        'correct_answer_letter' => 'A',
        'correct_answer' => 'Urgent surgical review for source control',
        'justification' => 'Postoperative peritonism after initial resuscitation suggests a surgical abdominal source requiring urgent source control.',
        'style_warnings' => [],
    ],
];

foreach ($scenarios as $key => $scenario) {
    $warnings = $scenario['style_warnings'];
    unset($scenario['style_warnings']);
    $q = array_merge($base, $scenario);
    $prompt = buildSbaAiReviewerPrompt($q, $warnings, []);
    echo "\n========== {$key} ==========\n";
    $fetch = formGeneratorOpenAiChatJsonQuestion(
        $prompt,
        '',
        0,
        0.35,
        formGeneratorOpenAiSbaReviewModel()
    );
    if (!$fetch['ok']) {
        echo 'FAIL: ' . $fetch['error'] . "\n";
        continue;
    }
    $norm = normalizeSbaAiReviewerResponse($fetch['data']);
    if (!$norm['ok']) {
        echo 'Normalize fail: ' . $norm['error'] . "\n";
        continue;
    }
    $r = $norm['data'];
    echo 'Readiness: ' . $r['overall_readiness_percent'] . '%  MLA: ' . $r['mla_compliance_percent'] . '%' . "\n";
    echo 'Ratings: clinical=' . $r['clinical_accuracy_rating']
        . ' OBA=' . $r['one_best_answer_rating']
        . ' skill=' . $r['skill_alignment_rating'] . "\n";
    echo 'Summary: ' . $r['short_tutor_summary'] . "\n";
    echo 'Agreed warnings: ' . implode(', ', $r['agreed_rule_warning_codes']) . "\n";
    echo 'False positives: ' . implode('; ', $r['possible_false_positive_rule_warning_codes']) . "\n";
    echo 'Independent: ' . implode('; ', $r['independent_concerns']) . "\n";
    echo 'Changes (' . count($r['recommended_changes']) . "):\n";
    foreach ($r['recommended_changes'] as $c) {
        echo '  - [' . $c['priority'] . '/' . $c['field'] . '] ' . $c['issue'] . "\n";
    }
}
