<?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';

$question = [
    'specialty' => 'Acute Medicine',
    'condition_name' => 'Sepsis',
    'presentation' => 'Septic shock',
    'year_level' => 'MLA Final Year',
    'summative_formative' => 'Summative',
    'skill' => 'Emergency Management',
    'tutor_comments' => '',
    'title' => 'Management of septic shock',
    'stem' => 'A 68 year old man with a history of type 2 diabetes attends the emergency department. His observations show temperature 39.1°C, pulse 118/min, blood pressure 82/48 mmHg, respiratory rate 24/min and oxygen saturation 91% on breathing air.',
    'lead_in' => 'What is the most appropriate immediate management?',
    'option_a' => 'Start IV fluids and broad-spectrum IV antibiotics',
    'option_b' => 'Administer IV fluids only',
    'option_c' => 'Initiate broad-spectrum IV antibiotics only',
    'option_d' => 'Request a full blood count and wait for results',
    'option_e' => 'Arrange a CT scan of the abdomen',
    'correct_answer_letter' => 'A',
    'correct_answer' => 'Start IV fluids and broad-spectrum IV antibiotics',
    'justification' => 'The underlying issue is septic shock requiring urgent resuscitation.',
];

$warnings = [
    [
        'code' => 'sepsis.emergency_formulaic_title',
        'severity' => 'high',
        'message' => 'Formulaic title “Management of …”.',
        'field' => 'title',
    ],
];

$prompt = buildSbaAiReviewerPrompt($question, $warnings, []);
$hasRef = stripos($prompt, 'MLA / MS AKT STYLE REFERENCE') !== false;
$hasEmergency = stripos($prompt, 'emergency management') !== false;

echo 'Prompt length: ' . strlen($prompt) . PHP_EOL;
echo 'Contains style reference: ' . ($hasRef ? 'yes' : 'NO') . PHP_EOL;
echo 'Contains emergency addendum: ' . ($hasEmergency ? 'yes' : 'NO') . PHP_EOL;

if (!$hasRef) {
    exit(1);
}

echo 'Calling AI reviewer...' . PHP_EOL;
$fetch = formGeneratorOpenAiChatJsonQuestion(
    $prompt,
    '',
    0,
    0.35,
    formGeneratorOpenAiSbaReviewModel()
);

if (!$fetch['ok']) {
    fwrite(STDERR, 'FAIL: ' . $fetch['error'] . PHP_EOL);
    exit(1);
}

$norm = normalizeSbaAiReviewerResponse($fetch['data']);
if (!$norm['ok']) {
    fwrite(STDERR, 'Normalize fail: ' . $norm['error'] . PHP_EOL);
    exit(1);
}

$review = $norm['data'];
$blob = strtolower(json_encode($review, JSON_UNESCAPED_UNICODE));
$checks = [
    'mentions formulaic title or Management of' => preg_match('/management of|formulaic|neutral.*title|title/i', $blob),
    'mentions history of or observations show or MLA wording' => preg_match('/history of|observations show|has\b|direct measurement/i', $blob),
    'mentions investigation option or FBC' => preg_match('/fbc|full blood count|investigation|ct scan/i', $blob),
    'recommended_changes count <= 5' => count($review['recommended_changes']) <= 5,
];

echo 'Summary: ' . ($review['short_tutor_summary'] ?? '') . PHP_EOL;
foreach ($checks as $label => $ok) {
    echo ($ok ? '[OK] ' : '[??] ') . $label . PHP_EOL;
}

echo json_encode($review, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . PHP_EOL;
