<?php

/**
 * Question generator — LLM prompt builders for the form-based workflow.
 * Loaded via app/ai/prompt_generator.php (backward-compatible entry point).
 */

/**
 * Sanitize optional tutor-supplied text for inclusion in LLM prompts (length limit, strip control chars).
 */
function embedPromptField($value, $maxLen = 8000) {
    $t = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/u', '', (string) $value);
    $t = trim($t);
    if (strlen($t) > $maxLen) {
        $t = substr($t, 0, $maxLen) . '…';
    }
    return $t;
}

/**
 * Infer a concise MLA-style presentation when the tutor leaves the presentation field blank.
 * Uses specialty, core condition, current skill, and optional tutor comments. Not called when the user supplied a non-empty presentation.
 */
function inferGeneratorPresentationMlaStyle(array $job): string
{
    $condition = mb_strtolower(trim((string) ($job['condition_name'] ?? '')));
    $specialty = mb_strtolower(trim((string) ($job['specialty'] ?? '')));
    $skill = trim((string) ($job['skill'] ?? ''));
    $tutor = mb_strtolower(trim((string) ($job['tutor_comments'] ?? '')));
    $blob = $condition . ' ' . $specialty;

    if ($tutor !== '') {
        if (preg_match('/\bcough\b/i', $tutor) && !preg_match('/\b(wheeze|sob|shortness|breathless|dyspnoea|dyspnea)\b/i', $tutor)) {
            return 'Cough';
        }
        if (preg_match('/\b(wheeze)\b/i', $tutor)) {
            return 'Wheeze';
        }
        if (preg_match('/\b(sob|shortness\s+of\s+breath|dyspnoea|dyspnea|breathless)\b/i', $tutor)) {
            return 'Shortness of breath';
        }
        if (preg_match('/\b(treatment\s+review|follow[-\s]?up|medication\s+review|chronic\s+review|review\s+clinic)\b/i', $tutor)) {
            return 'Treatment review';
        }
    }

    if (strpos($blob, 'asthma') !== false) {
        if (preg_match('/\b(Diagnosis|Investigation|Emergency Management)\b/i', $skill)) {
            return 'Wheeze';
        }
        if (preg_match('/\bInterpretation\b/i', $skill)) {
            return 'Peak flow and symptom pattern';
        }
        if (preg_match('/\b(Management|Prescribing)\b/i', $skill)) {
            return 'Treatment review';
        }
        if (preg_match('/\bMonitoring\b/i', $skill)) {
            return 'Asthma control review';
        }

        return 'Wheeze';
    }

    if (preg_match('/\b(copd|chronic obstructive)\b/i', $blob)) {
        if (preg_match('/\b(Diagnosis|Investigation|Emergency Management)\b/i', $skill)) {
            return 'Increased breathlessness and sputum';
        }
        if (preg_match('/\bInterpretation\b/i', $skill)) {
            return 'Spirometry and gas transfer results';
        }

        return 'Routine COPD review';
    }

    if (preg_match('/\b(type\s*[12]\s*)?diabetes|diabetic\b/i', $blob)) {
        if (preg_match('/\b(Diagnosis|Investigation|Emergency Management)\b/i', $skill)) {
            return 'Hyperglycaemic symptoms';
        }
        if (preg_match('/\bInterpretation\b/i', $skill)) {
            return 'Glycaemic and metabolic results';
        }

        return 'Routine diabetes review';
    }

    if (preg_match('/\b(ischaemic heart|acute coronary|myocardial infarction|acs|angina)\b/i', $blob)) {
        if (preg_match('/\b(Diagnosis|Investigation|Emergency Management)\b/i', $skill)) {
            return 'Acute chest pain';
        }

        return 'Post-event follow-up';
    }

    if (preg_match('/\b(Diagnosis|Investigation|Emergency Management)\b/i', $skill)) {
        return 'Typical acute presentation';
    }
    if (preg_match('/\bInterpretation\b/i', $skill)) {
        return 'Investigation results review';
    }
    if (preg_match('/\b(Management|Prescribing)\b/i', $skill)) {
        return 'Routine follow-up';
    }
    if (preg_match('/\bMonitoring\b/i', $skill)) {
        return 'Surveillance review';
    }

    return 'Clinical presentation for review';
}

/**
 * Comma-separated tags for INSERT into questions.tags (form-based generator).
 *
 * @return non-empty string
 */
function buildGeneratorQuestionTags(
    bool $presentationInferred,
    string $effectivePresentation,
    ?int $generationJobId = null,
    ?string $sepsisEmergencyScenarioSlot = null,
    ?string $peEmergencyScenarioSlot = null
): string {
    $parts = ['test', 'sba'];
    if ($presentationInferred) {
        $parts[] = 'presentation_inferred';
        $safe = trim(preg_replace('/\s+/u', ' ', str_replace(',', ';', $effectivePresentation)));
        if ($safe !== '') {
            $parts[] = 'inferred_presentation=' . $safe;
        }
    }
    if ($generationJobId !== null && $generationJobId > 0) {
        $parts[] = generatorFormBatchJobTag($generationJobId);
    }
    if ($sepsisEmergencyScenarioSlot !== null && $sepsisEmergencyScenarioSlot !== ''
        && function_exists('sbaSepsisEmergencyScenarioPlanTagFragment')) {
        $tagFrag = sbaSepsisEmergencyScenarioPlanTagFragment($sepsisEmergencyScenarioSlot);
        if ($tagFrag !== '') {
            $parts[] = $tagFrag;
        }
    }
    if ($peEmergencyScenarioSlot !== null && $peEmergencyScenarioSlot !== ''
        && function_exists('sbaPeEmergencyScenarioPlanTagFragment')) {
        $tagFrag = sbaPeEmergencyScenarioPlanTagFragment($peEmergencyScenarioSlot);
        if ($tagFrag !== '') {
            $parts[] = $tagFrag;
        }
    }

    return implode(',', $parts);
}

/**
 * First sentence (or short prefix) of the stem for batch anti-repetition context.
 */
function generatorStemOpeningSentence(string $stem): string
{
    $s = trim(preg_replace('/\s+/u', ' ', $stem));
    if ($s === '') {
        return '';
    }
    if (preg_match('/^(.*?[.!?])(\s|$)/u', $s, $m)) {
        return trim($m[1]);
    }
    $len = function_exists('mb_strlen') ? mb_strlen($s) : strlen($s);
    $cut = function_exists('mb_substr') ? mb_substr($s, 0, 180) : substr($s, 0, 180);
    if ($len > 180) {
        $cut .= '…';
    }

    return $cut;
}

/**
 * Compact age/sex snippet from stem opening when detectable (for anti-repetition guidance only).
 */
function generatorStemOpeningAgeSex(string $stem): string
{
    $open = generatorStemOpeningSentence($stem);
    if ($open === '') {
        return '';
    }
    if (preg_match('/\b(?:A|An|a|an)\s+(\d{1,3})\s+year[-\s]old\s+(man|woman|boy|girl|male|female)\b/u', $open, $m)) {
        return strtolower($m[1] . ' yo ' . $m[2]);
    }

    return '';
}

/**
 * @param list<array<string, mixed>> $priorRows
 */
function buildGeneratorBatchAntiRepetitionPromptBlock(array $priorRows, string $currentSkill, string $conditionName, string $presentation, string $jobSkillsCsv = '', string $tutorComments = '', array $job = []): string
{
    if ($priorRows === []) {
        return '';
    }

    $lines = [];
    $lettersUsed = [];
    $n = count($priorRows);
    $lines[] = 'BATCH ANTI-REPETITION (same tutor generation job — earlier items already saved)';
    $lines[] = 'The following ' . $n . ' item(s) were generated earlier in **this same job**. They **strongly constrain** this new item: treat them as mandatory diversity context — reuse **nothing** that reads as the same “clinical recipe” unless the learning outcome truly forces it.';
    $lines[] = 'The new item must stay faithful to the form inputs (specialty, core condition, presentation, learning outcome, year level, assessment type) and to the **Current skill**, while **actively varying** cues, framing, and keyed concept.';
    $lines[] = '';
    $lines[] = '**Multi-skill batches:** the **Current skill** in INPUTS is the only skill this item may assess; do not drift into assessing a different skill from the tutor’s rotation list.';
    $lines[] = '**Same core condition across the batch:** where Tutor comments do not fix the scenario arc, prefer a **different** internal framing than the earlier item(s), chosen from: **initial presentation**; **follow-up review**; **investigation result interpretation**; **treatment review**; **emergency presentation**; **monitoring review**; **complication recognition** — only when clinically proportionate and **safe** for the tested decision. Do **not** introduce unsafe or contrived clinical variation.';
    $lines[] = '';
    $lines[] = '**Batch variation (mandatory):**';
    $lines[] = '- Do **not** repeat the same **clinical cue cluster** across items (e.g. the same combination of night symptoms + reliever overuse + poor control + low-dose ICS narrative unless Tutor comments lock that pattern).';
    $lines[] = '- Do **not** repeat the same **keyed correct-answer concept** as any prior item unless unavoidable for fairness.';
    $lines[] = '- Do **not** reuse the same **management escalation** keyed concept (e.g. “add LABA”, “step up to LABA”, “LABA/ICS combination”) in more than one question in this job.';
    $lines[] = '- Do **not** reuse the same **lead-in pattern** or parallel template as a prior item (vary the question line while keeping the skill faithful).';
    if ($jobSkillsCsv !== '' && preg_match('/\bmonitoring\b/i', $jobSkillsCsv) && preg_match('/\bmanagement\b/i', $jobSkillsCsv)) {
        $lines[] = '- This job’s skill list includes **both** Management and Monitoring: a **Monitoring** item must **not** use the same **correct-answer concept** as a **Management** item elsewhere in the batch (e.g. both keyed on “add LABA”); Monitoring should focus on **review / control / safety monitoring**, not treatment escalation, unless **Tutor comments** explicitly ask for management-style stepping up.';
    }
    if ($jobSkillsCsv !== '' && preg_match('/\bemergency\s+management\b/i', $jobSkillsCsv) && preg_match('/\bmanagement\b/i', $jobSkillsCsv)) {
        $lines[] = '- This job’s skill list includes **both** **Management** and **Emergency Management**: they **must** test **different correct-answer concepts** in the same batch unless **Tutor comments** explicitly allow repetition. Do **not** key the same treatment priority twice (e.g. both **IV/broad-spectrum antibiotics**, both **aspirin**, both **IV fluid resuscitation**, both **oxygen therapy**). If **Management** already keyed antibiotics, **Emergency Management** should use a **distinct** acute priority where defensible (IV fluids for hypotension/shock, oxygen if hypoxic, urgent escalation/critical care review, source-control escalation when clearly indicated).';
    }
    $lines[] = '- **Interpretation vs Monitoring in one batch:** **Interpretation** = interpret **supplied data** in the stem with **interpretation-only** lead-ins and **interpretation** answer lines (no “follow-up measure”, “what should be reviewed?”, or action-verb options). **Monitoring** = choose what to **review or measure** at follow-up with **review/monitoring** options — do **not** reuse the same “review clinic” framing where the prior item already interpreted similar data.';
    $lines[] = '- **Keyed concept per skill:** across this job, **each skill** should test a **different correct-answer concept** (not the same “best next step” idea repackaged).';
    $lines[] = '- **Asthma-style cue load:** do **not** lean on the **same** combination of **increased reliever inhaler use** and **nocturnal / night symptoms** across **more than two** questions in this job unless Tutor comments lock that pattern; rotate other legitimate cues (exercise-induced symptoms, viral trigger, objective variability, technique, control scores, adherence, comorbid rhinitis, etc.).';
    $lines[] = '';

    $condLow = mb_strtolower($conditionName);
    if (strpos($condLow, 'asthma') !== false) {
        $lines[] = '**Asthma batch — skill separation (Current skill is mandatory; vary the keyed concept between skills):**';
        $lines[] = '- **Diagnosis (Core Condition = Asthma):** do **not** write that the patient **already has** or **is known to have** asthma in the stem (no “with asthma”, “known asthma”, “has asthma”, “established asthma” when the task is **making** the diagnosis). Prefer **recurrent or variable** cough, wheeze, or breathlessness over weeks or months; do **not** make **asthma exacerbation** (or acute exacerbation) the keyed diagnosis unless **Tutor comments** explicitly ask for that diagnosis. Options must be **diagnoses / disease entities**, including **Asthma** as **one** parallel option among plausible alternatives.';
        $lines[] = '- **Investigation:** do **not** put the **result** of the test you are asking for inside the stem. If the lead-in asks for the **initial** investigation, the stem must **not** already document **peak-flow variability**, **spirometry results**, or **bronchodilator reversibility** — keep the stem to presentation and background only; options are **investigations only**.';
        $lines[] = '- **Interpretation:** **key** = data-best interpretation; avoid unsupported **“significant”**; **justification** and **key** agree on control vs variability; prefer **variable / fixed obstruction**, **normal spirometry**, **restrictive pattern**, **poor control with variable obstruction**; **distinct** non-overlapping options.';
        $lines[] = '- **Monitoring:** **narrow lead-in** to one target (symptom control day-to-day, home PEF / variability, technique, etc.); **stem cue** favours the key; avoid broad lists where technique, adherence, lung function and symptoms all look equally correct.';
        $lines[] = '- **Emergency Management:** **acute severe asthma** presentation; options are **urgent actions**.';
        $lines[] = '- **Management:** **chronic** management steps (including appropriate escalation when the lead-in asks for management) — **not** “add LABA” as the keyed answer when the Current skill is **Monitoring** unless Tutor comments explicitly request escalation.';
        $lines[] = '';
    }

    if (preg_match('/\b(?:acute\s+coronary|coronary\s+syndrome|ischaemic\s+heart)\b/i', $conditionName)
        || stripos($condLow, 'nstemi') !== false
        || stripos($condLow, 'stemi') !== false
        || stripos($condLow, 'angina') !== false) {
        $lines[] = '**ACS / ischaemic chest pain batch — suggested skill mapping (vary keyed concepts across this job):**';
        $lines[] = '- **Diagnosis:** when **no ECG result and no troponin result** appear in the stem, key **acute coronary syndrome** (broader working diagnosis), **not** definite **myocardial infarction**, **STEMI**, or **NSTEMI**; do **not** justify MI from symptoms alone. Use **unstable angina** only when the stem clearly supports **troponin-negative** ischaemic pain. Key definite MI only when the stem documents **raised/positive troponin** or a **clear ST-segment elevation / STEMI** pattern.';
        $lines[] = '- **Investigation — Pattern A (initial):** no ECG performed or mentioned in the stem → lead-in asks for the **initial** investigation → key **12-lead ECG**. **Pattern B (next):** explicit ECG result in the stem (e.g. “ECG shows no ST-segment elevation”) → lead-in asks for the **next** investigation → key may be **cardiac troponin**. **Never** key troponin with ambiguous stem wording such as “ECG performed but results not yet available”, “ECG is pending”, or “ECG has been arranged”.';
        $lines[] = '- **Interpretation:** use **NSTEMI** / **STEMI** / **unstable angina** labels consistent with **ECG + troponin** data supplied; prefer **non-ST-elevation myocardial infarction** when troponin is **raised** and there is **no ST elevation**.';
        $lines[] = '- **Management:** keep vignettes **acute or recent** for **ACS**; do **not** default to **stable exertional angina** unless Tutor comments ask for that contrast; options must stay **ACS-relevant management**.';
        $lines[] = '- **Management vs Emergency Management:** **never** use the **same correct-answer concept** for both skills in one job (e.g. both “aspirin 300 mg orally”). If **Management** keys aspirin, **Emergency Management** must test a **different** urgent concept (reperfusion/cardiology pathway for STEMI, nitrate avoidance when hypotensive, oxygen only if hypoxic, immediate escalation if unstable). If **Emergency Management** keys aspirin, **Management** must use a **different** ACS management decision.';
        $lines[] = '';
    }

    if (preg_match('/\b(?:sepsis|septic\s+shock|severe\s+sepsis)\b/i', $conditionName)
        && $jobSkillsCsv !== ''
        && preg_match('/\bmanagement\b/i', $jobSkillsCsv)
        && preg_match('/\bemergency\s+management\b/i', $jobSkillsCsv)) {
        $lines[] = '**Sepsis batch — pre-assigned skill-concept map (see BINDING — SEPSIS BATCH SKILL-CONCEPT MAP in the main prompt):**';
        $lines[] = '- **Diagnosis** → syndrome vs **source of infection** separation (see BINDING — SEPSIS DIAGNOSIS); do **not** mix **Sepsis** with **Pneumonia** / **UTI** options unless the lead-in asks for **source**.';
        $lines[] = '- **Investigation** → **initial** vs **next** investigation alignment when urinalysis or other first-line results are already in the stem.';
        $lines[] = '- **Management** → **stable** suspected sepsis → key **broad-spectrum IV antibiotics** (not shock resuscitation bundle).';
        $lines[] = '- **Emergency Management** → rotate **scenario categories** (see BINDING — SEPSIS EMERGENCY MANAGEMENT): **at most one** fluids-plus-IV-antibiotics item; other items use vasopressor, source control, hypoxic resuscitation, or lactate/escalation keys — **not** repeating the same bundle line.';
        $lines[] = '- Do **not** weaken Emergency Management to avoid duplicating Management’s antibiotic concept.';
        $lines[] = '- **Style:** avoid **“history of”**, **“observations show”**, formulaic titles (**Management of …**, **Initial investigation in …**), repeated lead-ins, and uneven option lengths.';
        $lines[] = '';
    } elseif (preg_match('/\b(?:sepsis|septic\s+shock|severe\s+sepsis)\b/i', $conditionName)) {
        $lines[] = '**Sepsis batch — Management vs Emergency Management:** vary concepts; prefer combined resuscitation for unstable emergency items.';
        $lines[] = '';
    }

    if (function_exists('sbaCapPrescribingAppendBatchAntiRepetitionLines')) {
        sbaCapPrescribingAppendBatchAntiRepetitionLines(
            $lines,
            $priorRows,
            $currentSkill,
            $conditionName,
            $jobSkillsCsv,
            $tutorComments
        );
    }

    if (function_exists('sbaSepsisAppendBatchEmergencyAntiRepetitionLines')) {
        sbaSepsisAppendBatchEmergencyAntiRepetitionLines($lines, $priorRows, $currentSkill, $conditionName, $job);
    }

    if (function_exists('sbaPeAppendBatchMixedSkillAntiRepetitionLines')) {
        sbaPeAppendBatchMixedSkillAntiRepetitionLines($lines, $priorRows, $currentSkill, $conditionName, $jobSkillsCsv);
    }

    if (function_exists('sbaGeneratorConditionLooksCommunityAcquiredPneumonia')
        && sbaGeneratorConditionLooksCommunityAcquiredPneumonia($conditionName)
        && $jobSkillsCsv !== ''
        && str_contains($jobSkillsCsv, ',')) {
        $lines[] = '**Community-acquired pneumonia — mixed-skill batch mapping (vary keyed concepts; match Current skill):**';
        $lines[] = '- **Diagnosis:** competing diagnoses — not management or antibiotic options.';
        $lines[] = '- **Investigation:** investigations only; do not embed the result of the test being asked for.';
        $lines[] = '- **Interpretation:** match severity to stem data — physiological cues if keying severe CAP; do not overclaim severity from CRP/WBC/CXR alone.';
        $lines[] = '- **Management:** broader management strategies — avoid a full set of antibiotic drug names only (use **Prescribing** for antimicrobial choice).';
        $lines[] = '- **Prescribing:** antimicrobial options only; rotate CAP scenario slots across the batch.';
        $lines[] = '- **Monitoring:** monitoring parameters and treatment response — not one-off diagnostic work-up.';
        $lines[] = '- **Emergency Management:** unstable/hypoxic CAP — **oxygen plus** resuscitation when hypoxic; distinct from Management/Prescribing; no oxygen-only distractor unfairness.';
        $lines[] = '';
    }

    if (function_exists('sbaCapAppendBatchMixedSkillAntiRepetitionLines')) {
        sbaCapAppendBatchMixedSkillAntiRepetitionLines($lines, $priorRows, $currentSkill, $conditionName, $jobSkillsCsv);
    }

    if (preg_match('/\bpulmonary\s+embol/i', $conditionName)
        && $jobSkillsCsv !== ''
        && str_contains($jobSkillsCsv, ',')) {
        $lines[] = '**Pulmonary embolism — mixed-skill batch mapping (vary keyed concepts; match Current skill):**';
        $lines[] = '- **Diagnosis:** competing diagnoses only (PE, pneumonia, pneumothorax, ACS, etc.) — no management/investigation options; omit unnecessary “appears anxious”.';
        $lines[] = '- **Investigation:** tests only; **consistent demographics**; D-dimer vs CTPA aligned with pre-test probability in the stem.';
        $lines[] = '- **Interpretation:** when CTPA shows a **filling defect**, key **Pulmonary embolism** (definitive) — not only “high probability”; no treatment options.';
        $lines[] = '- **Management:** stable PE — anticoagulation at **one specificity level** (do not pair “initiate anticoagulation” with “start LMWH” unless testing that distinction).';
        $lines[] = '- **Emergency Management:** unstable/massive PE — reperfusion/escalation; **different** concept from Management; no CTPA/oral anticoagulant/monitor-only distractors unless testing unsafe sequencing.';
        $lines[] = '';
    }

    $i = 0;
    foreach ($priorRows as $row) {
        if (!is_array($row)) {
            continue;
        }
        ++$i;
        $title = trim((string) ($row['title'] ?? ''));
        $stem = (string) ($row['stem'] ?? '');
        $opening = generatorStemOpeningSentence($stem);
        $ageSex = generatorStemOpeningAgeSex($stem);
        $lead = trim((string) ($row['lead_in'] ?? ''));
        $letter = strtoupper(trim((string) ($row['correct_answer_letter'] ?? '')));
        $correct = trim((string) ($row['correct_answer'] ?? ''));
        $tags = trim((string) ($row['tags'] ?? ''));
        $skill = trim((string) ($row['skill'] ?? ''));
        if ($letter !== '' && preg_match('/^[A-E]$/', $letter)) {
            $lettersUsed[$letter] = true;
        }

        $lines[] = '--- Prior item ' . $i . ' (saved skill: ' . ($skill !== '' ? $skill : 'unknown') . ') ---';
        $lines[] = 'Title: ' . ($title !== '' ? $title : '(empty)');
        $lines[] = 'Stem opening sentence: ' . ($opening !== '' ? $opening : '(empty)');
        if ($ageSex !== '') {
            $lines[] = 'Detected age/sex framing (for variation only): ' . $ageSex;
        }
        $lines[] = 'Lead-in: ' . ($lead !== '' ? $lead : '(empty)');
        $lines[] = 'Correct answer letter: ' . ($letter !== '' ? $letter : '(empty)');
        $lines[] = 'Correct answer text: ' . ($correct !== '' ? $correct : '(empty)');
        $lines[] = 'Tags: ' . ($tags !== '' ? $tags : '(empty)');
        $opts = [];
        foreach (['A' => 'option_a', 'B' => 'option_b', 'C' => 'option_c', 'D' => 'option_d', 'E' => 'option_e'] as $lab => $key) {
            $t = trim((string) ($row[$key] ?? ''));
            if ($t !== '') {
                $opts[] = $lab . ': ' . $t;
            }
        }
        if ($opts !== []) {
            $lines[] = 'Options: ' . implode(' | ', $opts);
        }
        $lines[] = '';
    }

    $letterSummary = '';
    if ($lettersUsed !== []) {
        $letterSummary = 'Letters already used as the keyed answer in this batch: ' . implode(', ', array_keys($lettersUsed)) . '. ';
    }

    $lines[] = 'BATCH ANTI-REPETITION REQUIREMENTS FOR THIS NEW ITEM';
    $lines[] = $letterSummary . 'Where the **Current skill** and learning outcome allow more than one fair best answer or scenario shape, **prefer** a different **keyed letter** than the prior item(s); if only one letter remains clinically fair, keep clinical integrity over letter rotation.';
    $lines[] = '1) Do **not** reuse the same **title pattern** or template (vary neutral bank labelling; avoid parallel “Management of … / Initial investigation …” style hooks).';
    $lines[] = '2) Do **not** mirror the same **stem opening structure** (sentence order, cue stacking, or boilerplate rhythm) as any prior item in this batch.';
    $lines[] = '3) Where clinically fair, vary **age and sex** (and how they are introduced) relative to prior items; do **not** vary demographics in a way that changes the mandated condition, presentation, or unsafe implications.';
    $lines[] = '4) Do **not** repeat the same **lead-in wording** or parallel lead-in template; keep the task aligned with the **Current skill**.';
    $lines[] = '5) Prefer a different **keyed letter** when clinically equivalent options exist; otherwise follow one-best-answer discipline.';
    $lines[] = '6) Where the **Current skill** allows defensible variety (e.g. different investigations, management lines, or interpretations still faithful to the form), do **not** repeat the same **correct-answer concept** as a prior item unless the learning outcome effectively forces that same concept.';
    $lines[] = '7) Use **different distractor families** (different error types, different plausible alternatives) from prior items; keep options homogeneous in type per MS AKT rules.';
    $lines[] = '8) Do **not** reuse the same **clinical setting** (ED, GP, ward, clinic, etc.) unless the vignette or learning outcome **requires** that setting to make the best answer fair.';
    $lines[] = 'Remain consistent with **Core condition**: ' . ($conditionName !== '' ? $conditionName : '(as per INPUTS)') . ' and **Presentation**: ' . ($presentation !== '' ? $presentation : '(as per INPUTS)') . ' and with **Current skill**: ' . ($currentSkill !== '' ? $currentSkill : '(as per INPUTS)') . '.';
    $lines[] = '';

    return implode("\n", $lines);
}

/**
 * @return list<string>
 */
function aktYearLevelAllowedFormValues(): array
{
    return ['4', '5', '6'];
}

/**
 * Year-of-training label for curation only — must not alter clinical difficulty.
 */
function aktYearLevelMetadataNote($yearLevel): string
{
    $label = trim((string) $yearLevel);
    if ($label === '') {
        $label = 'unspecified';
    }

    return 'The selected year level (' . $label . ') is for tutor curation and output labelling only. '
        . 'Generate the question to the **same MLA-style MS AKT clinical standard** regardless of selected year. '
        . 'Do **not** make the vignette easier for Year 4 or harder for Year 6; do **not** change clinical complexity, '
        . 'distractor difficulty, or reasoning depth based on year level.';
}

function buildQuestionPrompt($job) {
    $specialty = embedPromptField($job['specialty'] ?? '');
    $condition = embedPromptField($job['condition_name'] ?? '');
    $presentation = embedPromptField($job['presentation'] ?? '');
    $skill = embedPromptField($job['skill'] ?? '');
    $learningOutcome = embedPromptField($job['learning_outcome'] ?? '');
    $skillsSelected = embedPromptField($job['skills'] ?? '');
    $summativeFormative = embedPromptField($job['summative_formative'] ?? '');
    $yearLevel = embedPromptField($job['year_level'] ?? '');
    $tutorComments = embedPromptField($job['tutor_comments'] ?? '');
    $yearMetadataNote = aktYearLevelMetadataNote($yearLevel);

    $presentationInferenceNote = '';
    if (!empty($job['_presentation_inferred'])) {
        $presentationInferenceNote = <<<'PRES_NOTE'

PRESENTATION NOTE
The **Presentation** line in INPUTS was **system-inferred** because the tutor left the presentation field blank. Treat that line as the mandated presenting problem for this item; do not substitute a different primary complaint unless **Tutor comments** explicitly override it.
PRES_NOTE;
    }

    $acsInvestigationSelectionInitial = '';
    $skillPlain = (string) ($job['skill'] ?? '');
    $tutorPlain = (string) ($job['tutor_comments'] ?? '');
    if (stripos($skillPlain, 'investigation selection') !== false && stripos($tutorPlain, 'initial investigation') !== false) {
        $acsInvestigationSelectionInitial = <<<'ACS_BLOCK'

BINDING LAYOUT FOR THIS ITEM (suspected acute coronary syndrome — Investigation selection with “initial investigation” in Tutor Comments)
- Follow **Pattern A** only (see **ACS Investigation — Pattern A / Pattern B** in MS AKT rules): the stem must contain **no ECG result** (no “ECG shows …”, “electrocardiogram shows …”, “initial ECG …”, ST-segment interpretation, or ECG arranged/performed/completed narrative).
- Include **ECG** or **electrocardiogram** (one consistent UK label) as **one** of the five answer options.
- Set the **correct** answer to that ECG / electrocardiogram option.
- The lead-in must ask for the **initial investigation** (consistent with Tutor Comments).
- Do **not** suggest that **troponin or other biomarkers should come before a first ECG** when **no ECG has yet been done** in suspected ACS.

If the stem **does** mention ECG as arranged, performed, completed, or reports ECG findings, then instead follow **Pattern B** only:
- The lead-in must **not** ask for the **initial investigation** — use **next investigation** / further investigation wording (e.g. “What is the most appropriate **next** investigation?”).
- The correct answer must **not** be ECG or electrocardiogram (usually **cardiac troponin** / high-sensitivity troponin in suspected ACS unless Tutor Comments specify otherwise).
- Remove **all** ECG finding wording from the stem if you still intend **ECG** as the key (**Pattern A**).

ACS_BLOCK;
    }

    $acsDiagnosisBinding = '';
    $conditionPlain = trim((string) ($job['condition_name'] ?? ''));
    if (preg_match('/^diagnosis$/i', trim($skillPlain))
        && preg_match('/\b(?:acute\s+coronary\s+syndrome|\bacs\b)\b/i', $conditionPlain)) {
        $acsDiagnosisBinding = <<<'ACS_DX_BLOCK'

BINDING — ACS Diagnosis (Core condition = Acute coronary syndrome; Current skill = Diagnosis)
- If the stem gives **no ECG result** and **no troponin result**, the **correct answer must be acute coronary syndrome** (or another label proportionate to pre-investigation evidence), **not** definite **myocardial infarction**, **STEMI**, or **NSTEMI**.
- Do **not** key **myocardial infarction** from **symptoms alone** (chest pain, diaphoresis, risk factors, etc.) without **confirmatory investigation data in the stem**.
- Use **acute coronary syndrome** as the broader diagnosis when the vignette suggests ACS but investigations are **not yet reported**.
- **Unstable angina** is appropriate only when the stem **clearly supports troponin-negative** ischaemic pain (explicit normal/negative troponin or equivalent framing).
- Key **STEMI**, **NSTEMI**, or definite **myocardial infarction** only when the stem already documents **raised/positive troponin** and/or a **clear ST-segment elevation / STEMI** pattern (not vague “ST changes” alone).
- The **justification** must **not** treat MI as proven without the same confirmatory data present in the stem.

ACS_DX_BLOCK;
    }

    $acsInvestigationBinding = '';
    if (preg_match('/^investigation(?:\s+selection)?$/i', trim($skillPlain))
        && preg_match('/\b(?:acute\s+coronary\s+syndrome|\bacs\b)\b/i', $conditionPlain)) {
        $acsInvestigationBinding = <<<'ACS_INV_BLOCK'

BINDING — ACS Investigation (Core condition = Acute coronary syndrome; Current skill = Investigation)
Use **exactly one** clean pattern:

**Pattern A — Initial investigation**
- The stem must contain **no ECG** performed, arranged, pending, or interpreted (no “ECG shows …”, no “ECG performed”, no “results not yet available”).
- The lead-in asks for the **initial** / **first** investigation.
- The correct answer is **12-lead ECG** (or **electrocardiogram**).

**Pattern B — Next investigation**
- The stem must include an **explicit ECG result** (e.g. “ECG shows no ST-segment elevation”, “ECG shows non-specific ST-segment changes”).
- The lead-in asks for the **next** investigation (never “initial” once an ECG result is in the stem).
- The correct answer may be **cardiac troponin**.

**Forbidden when keying troponin:** “An ECG is performed, but the results are not yet available”, “ECG has been arranged”, “ECG is pending”, or any ECG process wording **without** a readable ECG result in the stem.

ACS_INV_BLOCK;
    }

    $batchAntiRepetitionBlock = '';
    if (!empty($job['_batch_prior_questions']) && is_array($job['_batch_prior_questions'])) {
        $batchAntiRepetitionBlock = buildGeneratorBatchAntiRepetitionPromptBlock(
            $job['_batch_prior_questions'],
            (string) ($job['skill'] ?? ''),
            (string) ($job['condition_name'] ?? ''),
            (string) ($job['presentation'] ?? ''),
            (string) ($job['skills'] ?? ''),
            (string) ($job['tutor_comments'] ?? ''),
            $job
        );
        if ($batchAntiRepetitionBlock !== '') {
            $batchAntiRepetitionBlock = "\n" . embedPromptField($batchAntiRepetitionBlock, 14000) . "\n";
        }
    }

    $skillDefinitionBlock = '';
    if (function_exists('buildSbaGeneratorSkillPromptBlock')) {
        $skillDefinitionBlock = buildSbaGeneratorSkillPromptBlock((string) ($job['skill'] ?? ''), $job);
    }

    $sepsisConceptMapBlock = '';
    if (function_exists('buildSbaGeneratorSepsisSkillConceptMapBlock')) {
        $sepsisConceptMapBlock = buildSbaGeneratorSepsisSkillConceptMapBlock($job);
    }

    $sepsisInvestigationBlock = '';
    if (function_exists('buildSbaGeneratorSepsisInvestigationPromptBlock')) {
        $sepsisInvestigationBlock = buildSbaGeneratorSepsisInvestigationPromptBlock($job);
    }

    $sepsisDiagnosisBlock = '';
    if (function_exists('buildSbaGeneratorSepsisDiagnosisPromptBlock')) {
        $sepsisDiagnosisBlock = buildSbaGeneratorSepsisDiagnosisPromptBlock($job);
    }

    $sepsisEmergencyPlanBlock = '';
    if (function_exists('buildSbaGeneratorSepsisEmergencyScenarioPlanBlock')) {
        $sepsisEmergencyPlanBlock = buildSbaGeneratorSepsisEmergencyScenarioPlanBlock($job);
    }

    $sepsisEmergencyBlock = '';
    if (function_exists('buildSbaGeneratorSepsisEmergencyPromptBlock')) {
        $sepsisEmergencyBlock = buildSbaGeneratorSepsisEmergencyPromptBlock($job);
    }

    $peEmergencyPlanBlock = '';
    if (function_exists('buildSbaGeneratorPeEmergencyScenarioPlanBlock')) {
        $peEmergencyPlanBlock = buildSbaGeneratorPeEmergencyScenarioPlanBlock($job);
    }

    $peEmergencyBlock = '';
    if (function_exists('buildSbaGeneratorPulmonaryEmbolismEmergencyPromptBlock')) {
        $peEmergencyBlock = buildSbaGeneratorPulmonaryEmbolismEmergencyPromptBlock($job);
    }

    $peInvestigationBlock = '';
    if (function_exists('buildSbaGeneratorPeInvestigationPromptBlock')) {
        $peInvestigationBlock = buildSbaGeneratorPeInvestigationPromptBlock($job);
    }

    $peInterpretationBlock = '';
    if (function_exists('buildSbaGeneratorPeInterpretationPromptBlock')) {
        $peInterpretationBlock = buildSbaGeneratorPeInterpretationPromptBlock($job);
    }

    $capPrescribingBlock = '';
    if (function_exists('buildSbaGeneratorCapPrescribingPromptBlock')) {
        $capPrescribingBlock = buildSbaGeneratorCapPrescribingPromptBlock($job);
    }

    $capEmergencyBlock = '';
    if (function_exists('buildSbaGeneratorCapEmergencyPromptBlock')) {
        $capEmergencyBlock = buildSbaGeneratorCapEmergencyPromptBlock($job);
    }

    $capInterpretationBlock = '';
    if (function_exists('buildSbaGeneratorCapInterpretationPromptBlock')) {
        $capInterpretationBlock = buildSbaGeneratorCapInterpretationPromptBlock($job);
    }

    $capManagementBlock = '';
    if (function_exists('buildSbaGeneratorCapManagementPromptBlock')) {
        $capManagementBlock = buildSbaGeneratorCapManagementPromptBlock($job);
    }

    $capMonitoringBlock = '';
    if (function_exists('buildSbaGeneratorCapMonitoringPromptBlock')) {
        $capMonitoringBlock = buildSbaGeneratorCapMonitoringPromptBlock($job);
    }

    $prescribingOptionFormatBlock = '';
    if (function_exists('buildSbaGeneratorPrescribingOptionFormatPromptBlock')) {
        $prescribingOptionFormatBlock = buildSbaGeneratorPrescribingOptionFormatPromptBlock($job);
    }

    return <<<PROMPT
You are an experienced UK medical educator writing items aligned with the Medical Schools Council Applied Knowledge Test (MSC AKT / MS AKT) style: applied clinical Single Best Answer (SBA) questions for UK medical undergraduates.

TASK
Generate exactly ONE high-quality SBA item from the non-empty inputs below. **Tutor comments are optional steering**, not a required field: if the Tutor comments line is blank, infer a narrow task and scenario framing from the other inputs (see **TUTOR COMMENTS AND SCENARIO FRAMING** below). If Tutor comments are present, treat them as examiner steering notes and follow them except where they conflict with MS AKT rules, clinical safety, or the fixed form fields.
{$batchAntiRepetitionBlock}
INPUTS (use all that are non-empty)
- Specialty: {$specialty}
- Core condition (clinical focus): {$condition}
- Presentation: {$presentation}
- Skills list from tutor (rotation uses one skill per question; this question must use ONLY the Current skill below): {$skillsSelected}
- Current skill (the ONLY skill this item may assess): {$skill}
- Learning outcome / blueprint line (map the stem and answer to this): {$learningOutcome}
- Assessment type (Summative vs Formative): {$summativeFormative}
- Year of training (curation label from form — Year 4, Year 5, or Year 6 only): {$yearLevel}
- Year level (metadata only — do not change difficulty): {$yearMetadataNote}
- Tutor comments (optional examiner steering — may be empty): {$tutorComments}
{$presentationInferenceNote}
{$acsInvestigationSelectionInitial}
{$acsInvestigationBinding}
{$acsDiagnosisBinding}
{$skillDefinitionBlock}
{$sepsisConceptMapBlock}
{$sepsisDiagnosisBlock}
{$sepsisInvestigationBlock}
{$sepsisEmergencyPlanBlock}
{$sepsisEmergencyBlock}
{$peEmergencyPlanBlock}
{$peEmergencyBlock}
{$peInvestigationBlock}
{$peInterpretationBlock}
{$capPrescribingBlock}
{$capEmergencyBlock}
{$capInterpretationBlock}
{$capManagementBlock}
{$capMonitoringBlock}
{$prescribingOptionFormatBlock}
TUTOR COMMENTS AND SCENARIO FRAMING
When **Tutor comments** are absent (blank or whitespace only):
1. Infer **one** narrow decision point from **Specialty**, **Presentation**, **Core condition**, **Current skill**, **Year of training**, and **Assessment type** (Summative vs Formative); map stem, lead-in, and options to that single point.
2. Do **not** broaden beyond the **Current skill**; do not assess a different skill from the rotation list.
3. Avoid generic textbook questions; keep a realistic UK undergraduate vignette tied to the stated condition and presentation.
4. Select **one** suitable scenario framing from this internal catalogue (do **not** name the framing in the JSON—embody it in the writing): **initial presentation**; **follow-up review**; **investigation selection**; **interpretation of results**; **immediate management**; **treatment review**; **complication recognition**. Use only framings that genuinely fit the **Current skill** wording.
5. If a framing would stretch the skill, pick another from the list that fits.

**Controlled variation** (apply when Tutor comments are absent, and where present comments do not fix those choices):
6. Avoid repeating the same stem **structure** every time for the same core condition; vary narrative shape while keeping condition, presentation, and skill faithful to the inputs.
7. Vary plausibly: age/sex phrasing, which cue is emphasised, investigation timing, lead-in wording, and distractor families—without changing the underlying inputs or making discrimination arbitrary. Include **setting** (ED, GP, ward, etc.) **only** when it changes which option is best.
8. Do **not** vary the **core condition**, **presentation**, **Current skill**, or **year level** implied by the form.
9. Do **not** introduce randomness that would make more than one option clinically defensible as “best”; the keyed answer must remain uniquely best.
10. Keep all outputs **MS AKT style** and **valid JSON** with exactly the required keys.

When **Tutor comments** are present (non-empty):
11. Treat them as **examiner steering notes** (emphasis, nuance, exclusions, or layout hints)—not a replacement for the Current skill or learning outcome.
12. Follow them where they do **not** conflict with MS AKT style below, patient safety, or the non-negotiable form fields (Current skill, condition, presentation, year level, learning outcome).

MS AKT–STYLE RULES (overall)
- UK English; patient-focused; professionally appropriate tone; use UK clinical and undergraduate terminology throughout (FBC not CBC, ED not ER, **observations** not “vital signs”, presenting complaint not “chief complaint”). Use **British spelling** throughout (e.g. prioritised, hospitalised, recognised, **hypovolaemic** not “hypovolemic”, **ischaemia** / **ischaemic** not “ischemia”, **melaena** not “melena”/“malaena”, **oesophageal** not “esophageal”, **haematemesis**, **anaemia**, **oedema**). Use **gastro-oesophageal reflux disease** (with the **oesophageal** spelling and hyphenation), not US “gastroesophageal” forms. For blood gases in narrative, use **PO2**, **PCO2**, and **bicarbonate** with value and unit (e.g. **bicarbonate 28 mmol/L (22–26)**) — not **HCO3−** and not a dash after “bicarbonate”.
- In narrative stems, prefer **“observations”** (or naming measurements directly) rather than **“vital signs”** when reporting numbers.
- One clear decision point only; the item must assess ONLY the Current skill—do not embed a second major skill.
- Summative items: slightly higher stakes wording and discrimination; Formative items may include lighter scaffolding but remain rigorous.
- Five options labelled A–E; exactly one best answer; options parallel in length and grammatical form where possible.
- Correct answer: must require interpretation of the vignette, not isolated recall of an arbitrary fact.
- Avoid ultra-rare diseases and registrar-only detail unless the learning outcome explicitly demands it; align pharmacology and investigations with typical UK undergraduate teaching.

SKILL ALIGNMENT — **Current skill** controls the task (mandatory)
The **Current skill** in INPUTS determines what the **lead-in** asks for and what **type** every option (A–E) must be. Do **not** assess a different skill or mix task types.
- **Skill label consistency:** the assessed skill is **only** the **Current skill** line in INPUTS. The **title** must read as the **same** skill type (e.g. **Management** items use management-style titles and **management** option lines — not a **Prescribing**-only drug-choice item). When **Current skill** is **Management**, do **not** recast the task as **Prescribing** (and vice versa). Do **not** add extra JSON keys beyond those listed under OUTPUT; if any downstream field ever duplicates skill, it must **match Current skill exactly** (same wording), never a different skill name.

**Stem / lead-in split (all skills, non-negotiable):** Do **not** put the **exam question** inside the **stem**. The **stem** is **clinical narrative only** (history, examination cues, observations, and data already present in the vignette). The **lead-in** alone carries the **question** (usually one **“What …?”** or **“Which …?”** line ending with **?**). Never copy or paraphrase the lead-in task into the stem; Investigation stems must **not** include phrases such as “Which initial investigation …?” or “What investigation …?” inside the stem text.
- **Diagnosis:** use **symptoms and signs** that support a **likely diagnosis** among the options; every option must be a **diagnosis or disease entity**. When **Core Condition is Asthma** and the skill is **Diagnosis**, do **not** state in the stem that the patient **already has** asthma; do **not** key **asthma exacerbation** unless **Tutor comments** explicitly request exacerbation as the diagnosis; prefer **recurrent or variable** symptoms over weeks or months; include **Asthma** as **one** diagnosis option alongside plausible differentials. For other asthma-related diagnosis items, prefer **recurrent or variable** cough/wheeze/breathlessness over **weeks or months**, not a **single acute 1–3 day** attack in isolation, unless Tutor comments fix an acute-first presentation. For **upper GI bleeding / peptic ulcer** contexts: if the stem supports a **broad** diagnosis (e.g. **peptic ulcer bleed**) but does **not** localise **gastric** vs **duodenal** site, key **peptic ulcer bleed** or **peptic ulcer disease** (as the lead-in requires) — **not** **gastric ulcer** or **duodenal ulcer** unless the stem gives site-specific cues (e.g. gastric/antral/pyloric vs duodenal/bulb). **Respect Tutor comments** that say not to distinguish gastric from duodenal ulcer.
- **Management:** the lead-in asks for **management** or the **appropriate next step** in care; options must be **management steps** (homogeneous).
- **Emergency Management:** the stem should reflect an **acute** presentation; the lead-in asks for **immediate treatment** or **first / initial urgent action**; options must be **urgent actions** (homogeneous).
- **Investigation:** the lead-in states the investigation task (**initial**, **next**, **confirmatory**, or **monitoring** investigation); options must be **investigations / tests only** (homogeneous). Do **not** include the **result** of the investigation being asked for in the stem; for an **initial** investigation ask, the stem must **not** already report **peak-flow variability**, **spirometry results**, or **bronchodilator reversibility** — reserve those for **Interpretation** items. Avoid offering **two options that are effectively the same step in one diagnostic pathway** (e.g. spirometry plus bronchodilator reversibility testing described as separate “best” initial choices) **unless** Tutor comments make that distinction the explicit learning point.
- **Prescribing:** options must be **medicines or prescribing choices** consistent with the lead-in (homogeneous).
- **Monitoring:** the **lead-in must be specific enough to favour one monitoring target** — avoid broad “what to review?” lines where **symptom control**, **inhaler technique**, **adherence**, and **lung function** are all equally defensible. If the key is **symptom control**, ask about **day-to-day symptom control** monitoring; if the key is **inhaler technique**, the **stem** must include a **clear technique cue** (poor pMDI use, no spacer, repeated errors); if the key is **peak-flow variability**, ask about **objective variability** or **home PEF monitoring**. Options **may** be **review or monitoring actions** (homogeneous); do **not** include **treatment escalation** unless **Tutor comments** request **management**-style stepping up. Add **stem cues** so **one** option is **clearly** best. For **asthma**, do **not** list **inhaler technique**, **reliever use**, **peak-flow diary**, **adherence**, and **lung function review** as five interchangeable plausibles **without** one cue favouring the keyed answer.
- **Interpretation:** the **keyed answer must be the interpretation most directly supported by the supplied data** — do **not** hedge with vague intensity words such as **“significant”** unless the **numbers or thresholds** in the stem justify them. For **arterial blood gas** interpretation: if **pH is low**, **PCO2 is high**, and **bicarbonate is above the reference range**, acknowledge **possible metabolic compensation** (raised bicarbonate) while still identifying **respiratory acidosis** if pH remains low — do **not** write that bicarbonate is **within normal range** or that there is **no metabolic compensation**. In **COPD** with **raised bicarbonate** and **hypercapnia**, avoid simplistic labels such as **“acute respiratory acidosis with metabolic compensation”** — prefer **type 2 respiratory failure with respiratory acidosis** or **acute-on-chronic type 2 respiratory failure** when the stem/options support chronic hypercapnia. If the **justification** mainly argues **poor control**, the **correct answer** should include **poor control** (or an equivalent control statement), not a different primary label. The **stem must include actual data** (PEF diary **values**, spirometry, FeNO, scores, etc.) — do **not** narrate a test **was performed** without the **result**. The **lead-in must ask for interpretation** only (e.g. **“What is the best interpretation of these findings?”**); do **not** use follow-up / management / “next step” wording. For **asthma spirometry / peak-flow**, prefer **precise** parallel lines such as **variable airflow obstruction**, **poor control with variable airflow obstruction**, **fixed airflow obstruction**, **normal spirometry**, **restrictive pattern** — avoid **overlapping** options where **two lines could both be correct**. Options must be **distinct interpretations** at one **level** (data vs clinical implication) unless the lead-in makes mixing explicit. Do **not** pair **mild** and **severe exacerbation** labels **unless** the stem gives **formal severity criteria** or **Tutor comments** target grading. Do **not** start options with **assess**, **review**, **check**, **perform**, **increase**, **start**, **prescribe**, **refer**, **monitor**, **add**. The **title** must match the skill (e.g. **“Asthma peak-flow interpretation”**) — **not** “management assessment”.

**Interpretation vs Monitoring — lead-in and option family (mandatory):** **Interpretation** tests **meaning of supplied data**; **Monitoring** tests **what to do at follow-up**. Do **not** use Monitoring-style lead-ins or action options under **Interpretation**. Do **not** use interpretation-only lead-ins under **Monitoring**.

Skill-specific reinforcement (non-negotiable with Current skill):
- If **Diagnosis** → options must be **diagnoses** (or condition entities), not tests or treatments.
- If **Investigation** → options must be **investigations / tests** only; do **not** put **results** of the test being chosen in the stem when the task is **initial** testing; avoid redundant “same pathway” pairs unless that contrast is the teaching point.
- If **Interpretation** → **key** = interpretation **most directly supported** by the data; avoid vague **“significant”** without numeric support; if the **justification** stresses **poor control**, the **key** should too; use **precise** asthma airway labels (**variable / fixed obstruction**, **normal spirometry**, **restrictive pattern**, **poor control with variable obstruction**); **distinct** options only; **justification** matches the **key**; no action-verb option starts; **title** not management-style.
- If **Emergency Management** → acute stem; options are **urgent actions**.
- If **Management** → options are **management steps**.
- If **Monitoring** → **narrow lead-in** to the keyed target (day-to-day **symptom control** if that is the key; **objective variability / home PEF** for variability; **technique cue in stem** for technique); avoid broad lead-ins where **technique, adherence, lung function and symptoms** are all equally plausible; stem cues the **key**.
- Keep all five options in a **similar length band** (avoid one line much longer than the others).

MLA / AKT CONCISE EXAMINATION STYLE (prioritise alongside MS AKT rules below — faculty MLA practice)
1. Prefer concise stems of **40–80 words** where clinically possible; **avoid exceeding about 100 words** unless extra framing is essential to fairness or safety.
2. Build each item around **one clear clinical pivot** (one discriminating decision); every stem sentence should serve that pivot.
3. Do **not** add **setting** (ED, GP, ward, clinic, etc.) unless it **changes which option is best**.
4. Do **not** add **observations** unless they **change the answer**; if only one or two numbers or findings matter, give those only (still follow observation-order rules when you include them).
5. Do **not** add **past medical history**, **drug history**, or **social history** unless it **changes the answer** or supports a **plausible distractor** a borderline candidate might pick.
6. Avoid **redundant negatives** such as **“no other medical conditions”** unless that fact genuinely changes discrimination; **omit** negative boilerplate when it adds nothing.
7. For **Diagnosis** items (when **Current skill** is Diagnosis), do **not** name the **core condition** from the form in the stem.
8. For **Diagnosis** items, **avoid stacking every classic feature** together; give enough fair cues without a textbook giveaway list.
9. For **Investigation** items, make clear in the **lead-in** whether the question asks for an **initial**, **next** / further, **confirmatory**, or **monitoring** investigation (aligned with vignette timing).
10. Keep **answer options** short, **homogeneous**, and from the **same decision family** (all diagnoses, all tests, all management steps, etc.); do **not** mix decision families (for example diagnosis lines with investigation lines with treatment lines) in one option set. Keep lines in a **similar length band** so no single option dominates visually.
11. Use **plausible distractors** that a **borderline** student might seriously consider (common sequencing errors, partially right plans, adjacent diagnoses).
12. Avoid **weak distractors** that are obviously unrelated, absurd, or trivially dismissible for an MLA-style undergraduate item.
13. **Justifications** are concise **reviewer notes**, usually **about 3–4 sentences**, not teaching paragraphs; state why the key is best and why major distractors fail **for this vignette**.
14. Avoid tutor-like phrases such as **“The vignette presents”**, **“Option A is the best choice”**, **“directly addresses”**, and **“underlying issue”** in stem, lead-in, and justification.

1) MS AKT WORDING CONVENTIONS (apply to stem and options)
- Ages: do **not** hyphenate adjectival ages before a noun (e.g. “35 year old woman”, “6 month old infant”); predicative ages stay unhyphenated (e.g. “The patient is 65 years old”).
- Use man / woman / boy / girl for patients; avoid labelling patients as “male” / “female”.
- Prefer “full blood count” (FBC); avoid “complete blood count” (CBC).
- Avoid unnecessary “levels” after investigation names in stems, options, and justifications where it adds no meaning (e.g. write “cardiac troponin I” or “serum amylase”, not “… levels”); keep investigation options short, parallel, and homogeneous.
- Avoid the phrase “presents with”; use neutral clinical narrative instead.
- Avoid judgemental phrasing such as **“admits to”**; use neutral wording such as **“reports”**, **“describes”**, or **“says”** as appropriate.
- Avoid the phrase “on examination”; integrate findings without that formulaic opener.
- Oxygen: use “breathing air” rather than “room air” when describing supplemental oxygen context if relevant.
- If several medications are listed in the stem, list them alphabetically by generic name where sensible.
- For **eponymous signs** in prose, avoid **possessive apostrophes** (e.g. write **Murphy sign**, not “Murphy's sign”).

2) STEM QUALITY
- Short clinical vignette: **prefer about 40–80 words** where clinically possible; **avoid exceeding about 100 words** unless Tutor comments or safety require more (align with **MLA / AKT CONCISE EXAMINATION STYLE** above); begin with age and sex; present tense; third person; only clinically material detail.
- Anchor the stem on **one clinical pivot**; cut sentences that do not change which option is best among A–E.
- Do **not** add **observations** unless they **change the answer** for the lead-in; avoid **full observation sets** when only one or two measurements matter.
- Avoid **unrelated past medical history** that does **not** change which option is best for the lead-in; keep comorbidity detail **proportionate** to the tested decision.
- Avoid the phrase “history of” in the stem where you can; prefer compact comorbidity phrasing such as “has asthma”, “has type 2 diabetes mellitus”, or “has COPD”; do **not** use **“with known [condition]”** for current comorbidities; **omit** irrelevant comorbidity entirely when it does not affect discrimination.
- Avoid **redundant reassurance** such as **“no other medical conditions”** unless that fact genuinely changes discrimination; otherwise **omit**.
- Avoid unnecessary appearance or affect labels (e.g. “appears anxious”, “mildly anxious”) unless they change which option is correct for the lead-in.
- Realistic UK undergraduate clinical scenarios; name **setting** (ward, GP, ED, etc.) **only** when it changes which option is best for the lead-in (see **MLA / AKT CONCISE EXAMINATION STYLE**).
- Avoid textbook giveaway phrases that signal the diagnosis without reasoning.
- Build in at least two distinct clinical cues that must be weighed together (e.g. history plus investigation trend plus examination finding)—not a single cue that instantly solves the case.
- Omit clues that do not help discriminate between options; avoid padding or redundant sentences.
- Vary sentence rhythm; avoid repetitive “He has… She has…” cadence throughout.

**Diagnosis items** (when all options are diagnoses or the lead-in asks for the diagnosis / most likely condition)
- When **Current skill** is **Diagnosis**, do **not** name the **core condition** from the form in the stem (see **MLA / AKT CONCISE EXAMINATION STYLE**).
- Do **not** list every classic textbook feature together if that makes the keyed diagnosis trivially obvious; omit or soften non-discriminating “textbook complete” clustering.
- Where possible, **avoid stacking every classic cue** in a single vignette; keep only what forces discrimination among the options.
- Still require **interpretation of at least two clinically material cues** (history, examination, investigation trajectory, comorbidity, or setting) that must be integrated—not a single giveaway cue, but also **not** a kitchen-sink stem that loads every classic feature.
- For **diagnosis** items, avoid **stacking all classic features** for the keyed condition in one obvious list; keep **enough** cues for reasoning without a **textbook giveaway** stem.
- **Migraine:** avoid combining **unilateral or throbbing headache**, **nausea**, **photophobia**, and **visual aura** in one obvious cue list **unless** the learning point requires recognition of **typical migraine with aura**.
- Avoid weak or misleading **lifestyle or meal-timing cues** (e.g. “after eating”, “large meal”, “spicy food”) unless they genuinely change which diagnosis is most likely among the options.
- When options are parallel **diagnoses**, order them **alphabetically** or in another transparent logical order when that does not cue the correct answer (keep **correct_answer_letter** aligned with the true best option); if you use non-alphabetical order, make the ordering rule clinically self-evident from the vignette. For **short, parallel diagnosis labels**, prefer **alphabetical** order when safe.

**Blood tests and laboratory values** (when the stem cites blood tests or named biochemistry / haematology results)
- Give **numerical values with reference ranges** (or explicit comparison to stated normal/URL limits), not bare qualitative labels such as “elevated”, “low”, “raised”, “high”, or “abnormal” alone for those results.
- When you **do** give numbers, **do not also label** the same result as “elevated”, “raised”, “low”, “high”, or “abnormal” — let candidates interpret the value against the reference interval.
- Prefer the layout **Investigation value unit (reference range)** — e.g. **Amylase 620 U/L (60–180)** — not phrasing such as “normal range (60–180)”.
- Use an **en dash** (not a hyphen) between the lower and upper bounds of a numeric reference interval when written inline (e.g. **30–100 U/L**, **3.5–5.0 mmol/L**).
- Apply the same discipline to enzymes, electrolytes, inflammatory markers, troponin, and FBC parameters when they change discrimination.
- For **renal biochemistry / U&Es** in stems, when **several** of **sodium, potassium, urea, creatinine** are narrated, list them in this order: **sodium, potassium, urea, creatinine** (UK convention for readability).

**Interpretation of results, data-heavy stems, and acute kidney injury (AKI)**
- For **interpretation** items (including **interpretation of results**), the **stem** must give **enough clinical context** (history, examination, trajectory, or setting) to support the **keyed interpretation** — **not** bare abnormal numbers alone.
- For **pre-renal acute kidney injury**, include a **clear volume-depletion** or **hypoperfusion** cue where appropriate (e.g. **poor oral intake**, **diarrhoea**, **vomiting**, **dry mucous membranes**, **postural symptoms**, **hypotension**, or equivalent) so candidates can link creatinine / eGFR change to mechanism.
- In the **justification**, do **not over-claim**: do **not** infer **dehydration** or **pre-renal physiology** **solely** from **reduced urine output** / **oliguria** without other supporting cues already in the vignette.
- Prefer **“pre-renal acute kidney injury”** (or **pre-renal AKI**) over **“pre-renal azotaemia”** for undergraduate clarity unless the learning outcome specifically targets **azotaemia** wording.
- For **investigation-heavy** stems, put **each investigation on its own line** inside the stem string where the JSON format allows (e.g. newline characters between labelled blocks) so results remain readable.
- Keep **interpretation options** **homogeneous** (parallel labels or parallel categories); order **alphabetically** or in another **transparent logical** order when that does not cue the correct answer (keep **correct_answer_letter** aligned with the true best option).

**Acute pancreatitis** (when this is the clinical focus)
- If **serum amylase or lipase** is used **diagnostically**, the value must be **clearly at least three times the upper reference limit** (or the text must explicitly justify a lower threshold for a specific teaching point).
- Avoid weak alcohol cues such as **“20 units per week”** as a **major** pancreatitis clue; either use a **clinically meaningful** intake when alcohol genuinely matters, or **omit alcohol** if symptoms and amylase/lipase already support the diagnosis.
- Do **not** automatically stack **heavy alcohol context** + **classic pain radiating through to the back** + **markedly raised amylase/lipase** together unless each element is needed for discrimination; avoid over-determining the stem.
- Do **not** use vague phrases such as **“history of alcohol use”** without a **specific, relevant quantity** (e.g. units per week) when alcohol genuinely matters; otherwise omit the cue.

TITLE (the “title” JSON field — examiner metadata, not seen by candidates as a question)
- Keep titles **short (5–10 words)** where practical, **neutral**, and **grammatically complete**; they label the item for the question bank, not the task wording. **Word-count nudges** for titles are **low-priority housekeeping** only — clinical and skill alignment matter more.
- Titles must **not** reveal the keyed answer, the lead-in decision, or cue management over investigation (or vice versa).
- When **Current skill** is **Interpretation**, the title must **not** use **management** or **management assessment** style labelling; prefer **topic + interpretation** (e.g. **“Asthma peak-flow interpretation”**, **“Spirometry pattern in wheeze”**).
- Avoid formulaic or template titles such as “Management of X in Emergency Department”, “Initial investigation in suspected X”, “Diagnosis of X in Patient”, or similar “in Patient / in a Patient” hooks.
- Do **not** start the title with **“Management of …”**; prefer short neutral labels (e.g. “Conscious adult hypoglycaemia”, “Symptomatic hypoglycaemia treatment”, **“Suspected sepsis treatment”**, **“Febrile patient with shock”**).
- Prefer **compact neutral labels** that describe the clinical topic only, for example: “Chest pain assessment”, “Suspected acute coronary syndrome”, “Acute asthma treatment”, “Adult wheeze assessment”.
- Avoid dangling place fragments; do not hinge the title on “in Emergency Department” / “in emergency department”.

3) LEAD-IN QUALITY (mandatory — single clear lead-in matching **Current skill**)

**General rules**
- Write **one** clear lead-in only; it carries the exam question (never put the question in the stem).
- Match the **Current skill** exactly — the lead-in task and every option must be the same decision family.
- Use **“What …?”** for most lead-ins (MS AKT default).
- Use **“Which …?”** only when candidates can infer the five options from the stem **or** the range of possible answers is explicitly limited in the stem — otherwise use **“What …?”**.
- Avoid **negative** phrasing (e.g. “least likely”, “except”, “not”).
- Avoid vague lead-ins such as **“Which of the following is correct?”**, **“Which is the best option?”**, or **“What is the most appropriate management?”** when a more specific skill-aligned line exists.
- Do **not** use **“What is the single most …”** unless Tutor comments require that exact emphasis — prefer simpler wording (**“What is the most likely …”**, **“What is the most appropriate …”**).
- Vary lead-in wording across a batch — do **not** repeat the same stock template on every item.
- Pass **both cover tests**:
  1. A candidate should be able to **infer what kind of answer** is required from the stem **before** seeing the options (diagnosis vs test vs treatment vs interpretation).
  2. A candidate should **not** be able to answer correctly **without** reading the stem (the stem must supply discriminating facts).
- Assess only **one** decision point — no compound asks.

**Preferred patterns by skill** (adapt wording naturally; keep skill faithful):

| Skill | Preferred lead-in (examples) |
|-------|------------------------------|
| **Diagnosis** | What is the most likely diagnosis? |
| **Investigation** | What is the most appropriate **initial** investigation? — or, if the stem is **urgent** / time-critical: What is the most appropriate **urgent** investigation? — or, for **next** step after a result is already in the stem: What is the most appropriate **next** investigation? |
| **Interpretation** | What is the best interpretation of these findings? / What is the best interpretation of these results? |
| **Management** | What is the most appropriate next step in management? |
| **Prescribing** | What is the most appropriate medication to start? / What is the most appropriate medication to add? / What is the most appropriate treatment to prescribe? (match whether the key is new therapy, add-on, or switch) |
| **Emergency Management** | What treatment should be given first? / What is the most appropriate immediate treatment? — use wording that expects a **complete** urgent action in the key where needed; avoid lead-ins that invite partial-component keys when the stem implies a full emergency bundle |
| **Monitoring** | What should be monitored to assess response to treatment? / What is the most appropriate parameter to monitor? — **narrow** to one monitoring target; stem must cue the key |

**Special cases**
- If the keyed answer is a **risk score** or **assessment tool** (e.g. Glasgow–Blatchford, CURB-65, Wells score), ask for an **assessment tool** or **score**, **not** an “investigation”.
- If options are **medications**, the lead-in must ask about **treatment** or **prescribing**, not diagnosis or investigation.
- If options are **diagnostic labels**, the lead-in must ask for **diagnosis** (or most likely condition).
- If options are **interpretation statements**, the lead-in must ask for **interpretation** of supplied data.
- If the scenario is **unstable** or **time-critical**, the lead-in should make **urgency** clear (especially Investigation and Emergency Management).

**Stem versus lead-in (all items, especially prescribing)**
- Do **not** put the **exam question** inside the **stem**; the **stem** must contain **only** third-person **clinical narrative** (vignette, observations, and data already in the case). **Never** end the stem with a question mark or embed “Which …?”, “What …?”, or investigation-choice wording in the stem — that belongs **only** in the **lead-in**.
- The **lead-in** must contain the **question** (usually a single **“What …?”** or **“Which …?”** line ending with **?**).

**Prescribing** (when the Current skill involves prescribing, drug chart choices, or antimicrobial selection)
- Decide the **prescribing learning point** (see **BINDING — PRESCRIBING OPTION FORMAT**): **drug selection** (default), **route**, **dose**, **frequency/duration**, or **allergy/contraindication avoidance**.
- **Drug selection (default):** options are usually **drug names only** (e.g. **Amoxicillin**, **Doxycycline**, **Clarithromycin**) or **drug + route** when route matters — **not** full “mg + orally + TDS” on every line unless the item explicitly tests dose/frequency.
- **Dose / frequency items:** use the **same drug** (or clearly parallel regimens) across all five options; stem, lead-in, and **Tutor comments** must make dose or frequency the purpose.
- **Route items:** compare **routes** consistently across options.
- Avoid **granular doses**, **titration schedules**, or **complex frequency tables** in stems and options unless **Tutor comments** or the learning outcome **explicitly** requests dosing detail; undergraduate items usually test **drug class**, **route**, **first-line choice**, or **contraindication awareness** rather than arithmetic.
- Keep options in a **similar length band** — do not use four long regimen lines and one short drug name (or vice versa).
- Prefer **“takes no regular medication”** over **“is not on any medications”** when stating absence of regular drugs.
- Avoid **“significant past medical history”**; prefer **omitting** absent comorbidity entirely when it does not change discrimination, rather than negative boilerplate.
- If the **diagnosis** is already the **core condition** from the form, name it in the stem **only** where needed for **prescribing clarity** (e.g. allergy context, organ dysfunction); avoid wording that **gives away** the keyed option without reasoning.
- For **antibiotic** items, the **justification** should briefly note that **alternatives** may apply for **allergy** or **local guideline / micro** variation, while still explaining **why** the **keyed** choice is best **for this vignette**.

**Stable adult infection managed in the community** (when **Tutor comments** steer to a **stable** patient **treated in the community** — especially **community-acquired pneumonia**)
- Do **not** add features that imply **acute instability** or **routine hospital referral** (e.g. **hypoxaemia on air**, **hypotension**, **marked tachypnoea**, **new confusion**, **severe breathlessness**) unless the learning outcome explicitly tests **severity scoring** or **referral thresholds**.
- For **community-acquired pneumonia** managed in the **community**, avoid **oxygen saturation below about 94% on breathing air** unless the item deliberately tests **severity / oxygen need / referral**.
- Keep the vignette **aligned with the justification**: do **not** list **comorbidities** (e.g. **asthma**) in the stem if the justification claims **no significant comorbidities**; do **not** write **“absence of significant comorbidities”** in the justification if the stem already documents a **chronic condition** (e.g. asthma, COPD, heart failure, CKD, diabetes, immunosuppression).
- Avoid **asthma exacerbation** cues (e.g. **increased reliever / salbutamol use**) unless **asthma** is part of the **learning point** or clearly **material** to the prescribing decision.
- Keep **prescribing** items focused on **medicine choice** (class, first-line, allergy, key interaction), **not** on **severity triage** or **admission decisions**, unless **Tutor comments** or the learning outcome explicitly request that scope.
- For **stable uncomplicated community-acquired pneumonia**, use **clinical features that support outpatient / community treatment** (e.g. satisfactory observations on air, ability to mobilise or take oral therapy, absence of high-risk severity flags) rather than loading **red-flag** physiology.
- **First-line antimicrobial for stable mild CAP** without penicillin allergy, aspiration risk, recent antibiotics, or hospital-acquired context: prefer **amoxicillin** — **not** routine **co-amoxiclav** (see **BINDING — COMMUNITY-ACQUIRED PNEUMONIA PRESCRIBING** when Core condition is community-acquired pneumonia and Current skill is Prescribing).
- **Type 2 diabetes mellitus alone** (without complications) does **not** justify **co-amoxiclav** in stable mild CAP — key **amoxicillin** unless **penicillin allergy** or **atypical** features apply; do **not** justify co-amoxiclav from diabetes alone in the **justification** text.
- Use **doxycycline** or **clarithromycin** when **penicillin allergy**, **atypical infection**, or **Tutor comments** support a macrolide; use **co-amoxiclav** only when the stem (or Tutor comments) justify broader cover (**aspiration**, **frailty with concern**, **severe pneumonia**, **treatment failure**, **recent antibiotics**, **immunosuppression**, **hospital-acquired context**, or **diabetes with complications** — not diabetes alone).

**Monitoring** (when the **Current skill** is **Monitoring**, or the item tests **follow-up / repeat / surveillance** blood tests or observations)
- Do **not** put the **lead-in question** (e.g. “Which blood test …?”, “What is the most appropriate …?”) inside the **stem**; the **stem** stays **third-person vignette** only, and the **lead-in** alone carries the monitoring task.
- Avoid **second-person** framing such as **“you are responsible for”**, **“you should”**, or **“your patient”**; write in **consistent third person** (e.g. “She attends …”, “He is reviewed …”).
- Prefer **concise condition wording** (e.g. **“She has primary hypothyroidism”**) over wordy diagnosis phrasing (e.g. “has been diagnosed with primary hypothyroidism”).
- Prefer **concise treatment timing** (e.g. **“She started levothyroxine 8 weeks ago”**) over passive phrasing such as **“has been started on levothyroxine therapy”** unless a teaching point needs the passive voice.
- Use **“has no other medical conditions”** (or **omit** if irrelevant) rather than **“no other significant medical history”** when absence of extra comorbidity is **clinically material** to the decision; otherwise **omit** (see **MLA / AKT CONCISE EXAMINATION STYLE**).
- Prefer **UK-standard, named tests** (e.g. **TSH**, **free T4**, **Hb**, **U&Es** where appropriate) over vague panels such as **“thyroid function panel”**.
- Avoid **broad investigation labels** as options when a **narrower test** is the **intended best answer** (e.g. do **not** offer **“thyroid function tests”** or **“TFTs”** as a parallel option when **TSH alone** is the discriminating best test), unless the lead-in explicitly asks for a **panel** choice.
- For **monitoring** items, the **lead-in alone** must make clear **what is being monitored** (which analyte, observation, or follow-up interval) without repeating that task as a question in the **stem**.
- Do **not** write **“observations are normal”** or **“observations are within normal limits”**; if observations matter for the decision, give **numerical values** (or explicitly named findings); if they do **not** matter, **omit** them.
- Avoid **compound answer lines** that embed the **intended best test** plus extras (e.g. **“TSH and free T4”**) when the **keyed** discriminating answer is a **single** test (e.g. **TSH** alone); distractors should read as **clearly distinct** tests or monitoring approaches, **not** broader panels that **contain** the keyed test.
- In **justifications**, avoid **overclaiming** for **hypothyroidism / levothyroxine** monitoring: **TSH** reflects whether replacement is **proportionate / on track** — do **not** imply that **any** fall in TSH **automatically** means treatment is **effective** without tying it to **target range** and **clinical context**.
- Use **consistent thyroid test labels** in prose (e.g. **TSH**, **free T4** in sentence case); avoid mixing **Free T4**, **fT4**, and **FT4** arbitrarily in the same item unless a teaching point requires it.

4) DISTRACTOR QUALITY
- Options A–E must be homogeneous in type (all diagnoses, all investigations, all management steps, etc.—match the lead-in); **do not mix decision families** across the option set (see **MLA / AKT CONCISE EXAMINATION STYLE**).
- Where parallel option lists are safe to reorder without changing meaning, prefer **alphabetical** or another **transparent logical** order that does not cue the correct answer; keep **correct_answer_letter** aligned with the true best option. If non-alphabetical, make the ordering rule obvious from the vignette or option wording.
- Keep options short, in a similar length band, and parallel in structure so no single line dominates visually.
- Wrong answers must be plausible at MLA-style undergraduate level yet clearly inferior to the keyed option for this vignette—never jokes, absurd options, or obviously irrelevant alternatives; aim for options a **borderline** candidate might still consider before ruling out.
- Avoid distractors that are obviously insufficient for the severity painted in the stem (e.g. inhaler technique review alone in a hypoxic acute asthma attack) unless the item explicitly tests inappropriate reassurance or under-treatment.
- Prefer distractors that embody timing errors, sequencing errors, partially correct management, or common misconceptions relevant to the scenario.
- Avoid overlapping distractors; incorrect options wrong for substantive clinical reasons, not linguistic tricks.
- Avoid weak **ward-based reassurance** distractors such as **“monitor on the ward”** / **“monitor in the ward”**; prefer clearer **timing**, **sequencing**, or **under-treatment** errors, or where proportionate **“observe with analgesia”** / **“admit for observation”** wording instead of vague ward monitoring.
- For **sudden, severe, acute abdominal pain** presentations, avoid **implausible-slow** diagnoses (e.g. **pancreatic cancer**) as distractors unless the stem clearly supports that tempo; prefer **plausible acute abdominal pain differentials** (e.g. common surgical / medical emergencies and mimics at undergraduate level).

5) UK UNDERGRADUATE LEVEL
- Do not assign FY1-only autonomous responsibility or assume tasks reserved for junior doctors in postgraduate roles; frame decisions as appropriate for a senior medical student / finals candidate.
- Avoid specialist-only or tertiary-centre management pathways unless explicitly justified by the learning outcome.
- Maintain a **consistent MLA-style MS AKT standard** for all year labels; **Year of training** in INPUTS is for **curation/labelling only** — do **not** vary complexity, comorbidity load, or reasoning depth by year level.

6) CLINICAL REALISM
- Avoid stems where every clue aligns perfectly with only one diagnosis with no legitimate alternative reading.
- Allow mild ambiguity or competing plausible interpretations in the stem where appropriate, then let the lead-in force a single best answer among fair options.
- Avoid impossibly tidy “textbook” presentations every time; mild dose of real-world messiness is acceptable if discrimination remains fair.

**Investigation sequencing (general — all presentations, not only ACS)**
- If the lead-in asks for the **initial investigation**, the stem must **not** already report the **result** of that same first-line test (qualitative or numeric); either **omit** the result from the stem or change the lead-in to ask for the **next** / **further** investigation.
- If the stem already includes the **result** of an obvious **first-line** investigation, the lead-in should ask for the **next investigation** (or equivalent wording), not the **initial** investigation.
- **Amenorrhoea in a reproductive-age adult:** if **pregnancy** has **not** been excluded, the **initial** investigation is usually a **urine pregnancy test** (or equivalent β-hCG); if the stem already states a **negative urine pregnancy test** (or equivalent), the lead-in should ask for the **next** investigation, **not** the initial investigation.
- Avoid making a **single blood test** the keyed answer where **standard UK undergraduate practice** would usually start with a **small group** of initial endocrine (or related) tests, **unless** the stem and lead-in together make that **one** test clearly the best discriminating choice.

Investigation sequencing (suspected acute coronary syndrome — **choose exactly one pattern** when **Current skill** is **Investigation** and the clinical focus is suspected ACS or ischaemic chest pain)

**Pattern A — Initial investigation (ECG is the key)**
- The stem must contain **no ECG** at all — no result, no interpretation, and **no** process wording (no “ECG performed”, “ECG arranged”, “ECG pending”, “results not yet available”).
- The lead-in asks for the **initial** / **first** / **most appropriate initial** investigation.
- The **correct answer** is **12-lead ECG** / **electrocardiogram** (one UK label).

**Pattern B — Next investigation (troponin or other follow-on test may be the key)**
- The stem includes an **explicit ECG result** (e.g. “ECG shows no ST-segment elevation”, “ECG shows non-specific ST-segment changes”) — not merely that an ECG was done or is awaited.
- The lead-in asks for the **next** / **further** investigation — **never** “initial investigation” once an ECG result is in the stem.
- The **correct answer** may be **cardiac troponin**; **ECG must not** be the keyed answer.

**Mandatory exclusions (all ACS Investigation items)**
- **Do not** use ambiguous wording when keying **troponin**: “An ECG is performed, but the results are not yet available”, “ECG has been arranged”, “ECG is pending”, “ECG was performed” without a readable result, or similar. Either omit ECG from the stem (**Pattern A**) or give a clear **ECG shows …** read-out (**Pattern B**).
- **Never** include an **ECG result** (or interpreted ECG wording) in the stem when **ECG** / **electrocardiogram** is the **keyed** answer — if the key is ECG, strip **all** ECG findings from the stem (**Pattern A**).
- **Never** use an **initial investigation** lead-in when the stem already includes **any** ECG result or read-out (including “ECG shows …”, “electrocardiogram shows …”, “initial ECG …”) — switch to **Pattern B** wording and a non-ECG key.
- If the stem uses **“An ECG shows …”**, **“An initial ECG shows …”**, **“ECG shows …”**, or **“electrocardiogram shows …”**, the lead-in **must** use **next investigation** (or equivalent) and **ECG must not** be the keyed answer.
- Do **not** duplicate the same test under two labels in the option set (e.g. both “ECG” and “Electrocardiogram” as separate options); pick one consistent UK label.
- When every option is a parallel investigation list, order options **alphabetically** or in another **transparent logical** sequence that does not cue the correct answer (still set correct_answer_letter to the true best option). If you use non-alphabetical order, make the clinical sequence self-evident from the vignette.
- Prefer precise ECG wording such as “non-specific ST-segment changes” rather than vague phrases like “some non-specific ST changes”.
- In suspected **acute coronary syndrome**, avoid weak screening distractors such as **urinalysis** or **lipid profile** unless the vignette clearly makes them proportionate; keep investigations focused on acute cardiac assessment.

**ACS — interpretation, diagnosis, investigation, management, emergency (form generator)**
- **Core condition = Acute coronary syndrome (when INPUTS state this):** keep the **clinical story** aligned with **ACS** (suspected or confirmed after initial assessment, or an acute/recent cardiac ischaemia presentation). Do **not** make **stable angina** or **chronic exertional angina** the **main** framing unless **Tutor comments** or the **Current skill** explicitly asks for **differentiation** (e.g. stable angina vs ACS). If the stem describes **exertional pain relieved by rest** without acute ACS cues, do **not** write it as an ACS **Management** item unless the lead-in is clearly a **differential diagnosis** task.
- **Interpretation:** if **troponin is above the reference range** (or clearly **raised / positive**) with **ischaemic chest pain**, do **not** key or favour **unstable angina** — that pattern indicates **myocardial injury / infarction**, not unstable angina. **Unstable angina** should only be the **correct** answer when the stem shows troponin is **not raised** / **normal** (or the vignette is explicitly framed for true troponin-negative unstable angina). If the **ECG** shows **ST depression**, **non-specific ST changes**, or **no ST elevation** and troponin is **raised**, prefer **non-ST-elevation myocardial infarction (NSTEMI)** as the keyed label where appropriate — avoid vague lines such as **“myocardial infarction likely due to raised troponin”** without using the **NSTEMI** / **non-ST-elevation MI** wording when that is the teaching intent. Do **not** put **“myocardial infarction”** and **“myocardial injury”** (or near-synonyms) in the **same** option set — they overlap for candidates. Prefer **distinct** interpretation options drawn from this family where possible: **NSTEMI**, **STEMI**, **unstable angina**, **stable angina**, **non-cardiac chest pain** (adapt to the vignette).
- **Diagnosis (acute coronary syndrome):** if **no ECG result and no troponin result** appear in the stem, key **acute coronary syndrome** — **not** definite **myocardial infarction**, **STEMI**, or **NSTEMI**; do **not** justify MI from **symptoms alone**. Key definite MI labels only when the stem documents **raised/positive troponin** and/or **ST-segment elevation / STEMI**. Use **unstable angina** only when the stem supports **troponin-negative** ischaemic symptoms. Do **not** argue that **MI is excluded** because **troponin is normal / not elevated** unless the stem **reports** troponin status. Avoid **stacking every classic MI cue** in one stem.
- **Investigation (ACS / suspected ischaemic chest pain):** use **exactly one** of **Pattern A** or **Pattern B** from **Investigation sequencing (suspected acute coronary syndrome …)** above — do **not** mix them. **Never** key **troponin** without an explicit **ECG shows …** result in the stem; **never** use pending/arranged/performed-without-result ECG prose when troponin is the key. **Never** key **ECG** if the stem already contains an ECG read-out. Align with the **ACS Investigation binding block** when present. Do **not** offer **exercise tolerance testing** in **acute** chest pain unless the scenario is **stable and non-acute**.
- **Management vs Emergency Management (any batch):** **never** repeat the **same correct-answer concept** or the **same treatment family** (antibiotics, aspirin, IV fluids, oxygen, etc.) across **Management** and **Emergency Management** in one job unless **Tutor comments** explicitly allow repetition. **Exception (sepsis):** **Management** may key **antibiotics only** while **Emergency Management** keys a **combined sepsis resuscitation** line (IV fluids **plus** IV antibiotics / bundle) — related but **not** identical; do not force Emergency Management to fluids-only to avoid duplication.
- **Management (when Current skill is Management):** **every** option must be a **management / treatment** action — do **not** list **investigations** (e.g. **ECG**, **chest X-ray**, **troponin**, **serial troponin**) as options. If **aspirin** is the intended key, do **not** use essential investigations as distractors; use **treatment-only** distractors (e.g. **nitrates**, **morphine**, **beta-blocker**, **anticoagulation**, **oxygen**) where clinically appropriate. When **Core condition** is **acute coronary syndrome**, frame **suspected or confirmed ACS after initial assessment**; keep the scenario **acute or recent**, not a **chronic stable exertional angina** review unless Tutor comments explicitly request that contrast; options must be **ACS-relevant management** (not generic long-term stable-angina care unless that is the stated learning point). The stem must state clearly that **ACS is suspected after initial assessment** and there is **no contraindication** to **aspirin** (or antiplatelet) if that is the key.
- **Emergency management (Current skill Emergency management; core condition acute coronary syndrome):** the **stem must never contain the exam question** — no “What is the most appropriate …?” or “Which …?” in the **stem**; put **all** question wording in the **lead_in** only. Pick **one** teaching frame — **(a)** immediate **antiplatelet** in **stable** suspected ACS; **(b)** **urgent escalation / reperfusion** when the stem has **ST-segment elevation**, **STEMI**, or **hypotension**; **(c)** **unsafe treatments** (e.g. **nitrates** when hypotensive, **RV infarct** / fluids). **Do not auto-rewrite** the keyed answer in tooling — if the vignette breaks one-best-answer discipline, **revise stem, options, and key together** (warnings flag issues only).
  - **If the intended correct answer is aspirin:** generate a **haemodynamically stable** suspected ACS patient only. **Stable** means the stem and options must **avoid**: **hypotension** or **systolic BP under 100 mmHg**; **ST-segment elevation** or **STEMI** wording; **inferior STEMI** / inferior ST-elevation cues; **shock**, **collapse**, **syncope**, or **altered consciousness**; **urgent cardiology review**, **primary PCI / PPCI pathway**, **reperfusion**, or **IV fluids** as **options** (they compete with antiplatelet as “immediate” steps). Use aspirin as key only where **immediate antiplatelet** is clearly the best action for the lead-in.
  - **If the stem includes ST-segment elevation, hypotension, or STEMI:** do **not** key **aspirin** (unless the lead-in **explicitly** targets **immediate antiplatelet therapy** alone). Key **urgent cardiology review**, **primary PCI pathway activation**, or another **single best reperfusion / escalation** line to match the wording. Keep **all options** in that **escalation family**. Do **not** include **IV fluids** unless **right ventricular infarction** or **fluid-responsive hypotension** is the **learning point**.
  - **If the keyed answer is primary PCI, urgent PCI, reperfusion, or a cardiology pathway:** the stem **must** include clear **ST-segment elevation on ECG** (precise territory wording, e.g. “ECG shows ST-segment elevation in leads II, III and aVF”) or another explicit reperfusion indication (e.g. hypotension with inferior STEMI); do **not** key reperfusion from symptoms alone without ECG STE evidence.
  - **Inferior ST elevation in leads II, III and aVF with hypotension:** do **not** key **aspirin** as the sole best answer — either key **urgent cardiology / reperfusion**, or reframe the item to test **nitrate avoidance** / **right ventricular infarction** with a matching key and options.
  - **Treatment or management lead-in (Emergency management — strict):** when the **lead-in** contains **management**, **treatment**, **therapy**, **immediate action**, **first action**, **immediate management**, **immediate treatment**, **most appropriate management**, or equivalent **appropriate … management** wording, **every** option must be a **treatment** or **immediate therapeutic** action — **do not** include **investigation** or **imaging** options. **Prohibited option wording** (and close variants) includes: **ECG**, **electrocardiogram**, **troponin**, **chest X-ray**, **X-ray**, **CT**, **scan**, **imaging**, **investigation**, **test** (when used as a diagnostic test), **repeat** troponin, **serial** troponin, **echocardiogram** when ordered as a test, **ultrasound** when diagnostic, **V/Q scan**, **D-dimer**, **blood tests** as the option line. If any investigation is needed in the vignette, switch the **lead-in** to **initial assessment** / **first investigation** / **next investigation** instead of treatment/management. **Do not auto-repair** options in tooling — if the option set is wrong, **rewrite options** in the model output.
  - **Stable suspected ACS with aspirin as the key:** **all** options (including distractors) must be **treatment-only** — use plausible alternatives such as **sublingual nitrate**, **intravenous morphine**, **oxygen therapy**, **beta-blocker therapy**, **therapeutic anticoagulation** (and similar), **not** tests or imaging. Frame distractors as **realistic adjuncts** that are **clearly lower priority than immediate aspirin** for this lead-in (symptom relief, co-morbidity caution, or later steps), not as equally “first” actions. Where a nitrate is named in UK style, prefer **glyceryl trinitrate** (GTN) rather than **nitroglycerin**. **Do not** use **chest X-ray** (or **CXR** / plain **X-ray**) as an option when the lead-in asks for **treatment** or **management** as above.
  - **ECG wording:** avoid vague phrases such as **“there are indications of ST-segment elevation”**. Use **precise** territory wording (e.g. **“ECG shows ST-segment elevation in leads II, III and aVF”**) or **omit** ECG detail if not needed.
  - Keep **all options** in the **same emergency decision family**. Do **not** use weak **senior review** distractors when still clinically defensible in instability.
- **ACS wording and layout:** avoid **“vital signs show”**; give **observations** in **MS AKT order** (temperature, pulse, blood pressure, respiratory rate, oxygen saturation) with numbers where they matter. Avoid **“history of chest pain”** / **“history of central chest pain”**; use **“has chest pain”**, **“has had chest pain”**, or narrative of the **current** episode. Avoid **“appears anxious”** and **“no significant past medical history”** unless they change discrimination. Use **“breathing air”**, not **“on air”**, for room-air saturations. Keep ACS **options short** and in a **similar length band**.
- **ACS justification phrasing:** write short clauses as **grammatical sentences** where an adjective follows a noun (e.g. **“oxygen saturation is normal”**, **“oxygen saturation is 98% breathing air”**), not bare fragments such as **“oxygen saturation normal”**. When **immediate aspirin** is the keyed answer, do **not** justify **glyceryl trinitrate (GTN)** or other anti-anginal measures as **equally suitable first immediate treatment** — describe them as **adjunct symptom relief** or **second-line** unless the item explicitly tests nitrate strategy.

7) ACUTE MANAGEMENT, OXYGEN, OBSERVATIONS, AND ONE-BEST-ANSWER DISCIPLINE (when the stem or options involve acute illness, emergency management, resuscitation, or oxygen therapy)

Dosing and units (stem, options, justification)
- Use a **space between the number and the unit** (e.g. **15 g**, not “15g”; **10 mL**, not “10mL”).
- Avoid unnecessary **“of”** after dose units when the next word is the substance (e.g. **“15 g glucose orally”**, not “15 g of glucose orally”).
- For **blood glucose** in narrative, prefer concise wording such as: **“Capillary blood glucose is 2.5 mmol/L (4.0–7.8).”**

Emergency management options (SBA)
- For **hypoglycaemia** when **oral glucose** (tablets, powder, gel, or equivalent concentrated oral glucose) is the **keyed** best step, do **not** include **any other oral carbohydrate** as a distractor — specifically avoid **fruit juice**, **orange juice**, **sugary or carbohydrate drinks**, **glucose gel** as a parallel “oral sugar” choice, **oral sugar**, or similar **acceptable alternative oral treatments**; they can both be defensible at undergraduate level and break one-best-answer discipline.
- Distractors should test **wrong route**, **wrong timing**, **under-treatment**, or **need for escalation** (e.g. IM glucagon, IV glucose where appropriate), **not** a second clinically acceptable oral carbohydrate alongside oral glucose.
- For **conscious, symptomatic hypoglycaemia**, prefer a **capillary / blood glucose clearly below 4.0 mmol/L** and consistent with the scenario (commonly about **2.5–3.2 mmol/L** unless a teaching reason specifies otherwise).
- Avoid unnecessary **prescribing complexity** (e.g. detailed **IV glucose concentration** regimens) unless the learning outcome explicitly tests that choice.

**Suspected sepsis — Investigation (when Current skill is Investigation)**
- Distinguish **diagnostic/source investigation** (blood cultures, urinalysis, chest X-ray, wound swab, etc.) from **severity/risk markers** (lactate, prognostic scores) and from **monitoring** tests.
- When the lead-in asks for the **initial** / **first** / **most appropriate initial investigation**, key a **diagnostic or source** test fitting the stem — commonly **blood cultures**; also **FBC**, **urinalysis**, **chest X-ray** as context dictates — **not lactate alone** unless the stem explicitly focuses on **perfusion**, **shock severity**, or **severity assessment**.
- If the stem already reports **urinalysis**, **blood culture**, or another **first-line result**, use a **next investigation** lead-in or **omit** the result from the stem — do **not** ask for the **initial** test again.
- Reserve **lactate** for lead-ins about **severity**, **risk stratification**, **prognosis**, **shock assessment**, or **Interpretation** of a supplied lactate value — not generic “initial investigation in suspected sepsis”.

**Suspected sepsis — Diagnosis (when Current skill is Diagnosis)**
- **Syndrome diagnosis:** key **Sepsis** (or **septic shock** only if shock is clear) — options must be **competing acute diagnoses** (e.g. anaphylaxis, cardiogenic shock, hypovolaemia, pulmonary embolism) — **not** a mix of **Sepsis / severe sepsis / septic shock / pneumonia / ARDS**. Avoid **severe sepsis** as a routine option.
- **Source diagnosis:** when the lead-in asks for **source of infection**, **all options** must be **sources** — **Sepsis** must **not** be an option.

**Suspected sepsis (management and emergency management)**
- **Management:** it is acceptable to key timely **broad-spectrum IV antibiotics** in **stable** or **suspected sepsis** when that matches the lead-in.
- **Emergency management — scenario categories (mandatory in multi-item batches):** assign **one category per item** before varying wording — **at most one** **initial resuscitation** key (**IV fluids plus broad-spectrum IV antibiotics**). Other categories: **refractory hypotension** (vasopressor after fluids/antibiotics given in stem), **source control** (obstructed infected kidney), **hypoxic sepsis** (oxygen plus resuscitation), **lactate/perfusion escalation**. See **BINDING — SEPSIS EMERGENCY MANAGEMENT**.
- **Emergency batch:** five **distinct scenario categories** before repeat; **no duplicate noradrenaline**; varied lead-ins; neutral titles; options in a **similar length band** with **subtler** sequencing distractors (not withhold-until-cultures / oxygen-only throwaways); avoid “history of”, “observations show”, “vital signs”, “underlying issue” in justification.
- **Do not** weaken keys (e.g. fluids plus monitor without antibiotics) to avoid duplicating Management’s antibiotic concept.
- If the lead-in asks for the **first action** in **isolated hypotension**, **IV fluids** may be correct — but the **stem and lead-in** must make that **narrow circulatory** task explicit.
- If the lead-in asks for **immediate management of suspected septic shock** (or equivalent), use a **combined** emergency management answer.
- Do **not** delay **IV antibiotics** to wait for **investigation results** (including blood cultures, imaging, or “complete work-up”) when the stem describes **suspected sepsis** needing urgent treatment; investigations can run **in parallel** without postponing empirical therapy.
- Prefer explicit **“IV antibiotics”** or **“broad-spectrum IV antibiotics”** rather than vague **“broad-spectrum antibiotics”** (route should be clear for sepsis emergencies).
- Distractors may include **plausible sequencing errors** (e.g. **withholding antibiotics until cultures return**, **imaging before treatment** when unstable); avoid options that teach unsafe delay in **hypotensive / shocked** sepsis unless the item explicitly tests that error.

**Pulmonary embolism — Emergency Management (when Core condition is Pulmonary embolism and Current skill is Emergency Management)**
- **Do not** apply **sepsis** emergency templates: **no broad-spectrum IV antibiotics** and **no “IV fluids plus antibiotics” sepsis bundle** unless the stem clearly indicates **infection** (sepsis, pneumonia, confirmed bacterial source).
- **Thrombolysis / reperfusion keys:** the stem **must** include **haemodynamic instability** (e.g. **systolic BP under 90 mmHg**, **shock**, **cardiac arrest**, obstructive / circulatory collapse). **Hypoxia alone is not enough** to key thrombolysis.
- **Hypoxic but stable (no shock / hypotension):** usually key **oxygen plus anticoagulation** (e.g. LMWH) and/or **urgent escalation** — **not thrombolysis**; thrombolysis may be a **distractor** only.
- **Shock / hypotension with suspected massive or high-risk PE:** key **thrombolysis / reperfusion** or **urgent senior / critical care-led reperfusion** — **not antibiotics**; **not anticoagulation alone** when shock is present.
- **Lead-in for reperfusion keys:** target **definitive emergency treatment** or **life-threatening cause** / **massive PE with shock** — avoid generic **“immediate management”** alone when SpO₂ is low, or oxygen will unfairly compete with thrombolysis.
- **Hypoxia with shock:** if the lead-in stays generic and the patient is hypoxic and shocked, key **oxygen plus reperfusion/escalation** in one line **or** omit **standalone oxygen therapy** as a distractor.
- **Stable non-shocked PE:** anticoagulation (with oxygen if hypoxic) may be the keyed immediate treatment when clinically appropriate.
- **Options:** emergency **actions** only — **no CTPA**, **V/Q scan**, or **D-dimer** when the lead-in asks for **immediate management**.

**Suspected ectopic pregnancy and unstable gynaecological emergencies**
- Do **not** **name the diagnosis outright** in the **final sentence** of the stem (e.g. avoid “She is suspected to have a **ruptured ectopic pregnancy**.”); let the **lead-in** ask the management task while the stem supplies **enough cues** (pain, bleeding, risk factors, observations) for candidates to **infer** the problem and **urgency**.
- Where the scenario is **ectopic pregnancy**, include **pregnancy status** when it matters — prefer **“A urine pregnancy test is positive”** (or equivalent) or a **gestational age / dating** cue where appropriate, rather than vague **“known to be pregnant”**, unless the latter is clearly the clearest wording for the vignette.
- When the patient is **unstable** with suspected **ruptured ectopic**, the **keyed answer** should **not** be **IV fluids alone** unless the **lead-in** narrows the task to the **first resuscitation action only** (e.g. the single immediate circulatory step); otherwise prefer a **single best line** that **combines** **immediate resuscitation** (e.g. IV access / **IV fluids** as appropriate) with **urgent gynaecology / surgical escalation** — **without** specialist operative detail, e.g. **“Start IV fluids and arrange urgent gynaecology review.”**
- Use **plausible sequencing-error distractors** where appropriate, for example: **intramuscular methotrexate**; **repeat serum β-hCG in 48 hours**; **urgent ultrasound before resuscitation**; **outpatient early pregnancy unit review**; **observation with analgesia alone** — not irrelevant generic kit (see below).
- Avoid **implausible** or **off-topic** distractors such as **nasogastric tube** unless the vignette makes it genuinely proportionate.
- When giving **observations**, use **MS AKT order** (temperature, pulse, blood pressure, respiratory rate, oxygen saturation) and **numeric pulse / BP / RR / saturations** where they matter; avoid vague compressed phrasing such as **“tachycardic with a pulse”** — write the **pulse rate** in the observation sentence.
- Keep **management options** in a **similar length band** where possible so one line does not dominate visually.
- For the **title** field, follow the global title rules above — in particular **do not** begin with **“Management of …”**; use a short neutral topic label (e.g. “Unstable early pregnancy pain”, “Suspected ectopic pregnancy”).

Clinical one-best-answer protection
- If the stem describes hypoxia (including SpO₂ under about 92% on breathing air or equivalent), do not offer “oxygen only” as a competing distractor unless the keyed correct answer genuinely involves oxygen escalation OR the lead-in explicitly asks for the single most disease-specific immediate treatment (not generic resuscitation steps).
- Design options so that only ONE immediate action is clearly best for the lead-in; avoid pairs of options that could both be legitimately chosen as immediate management at the same time point.
- For acute asthma with oxygen saturation below about 92% on breathing air, either make escalation that includes controlled oxygen part of the correct answer, or omit standalone oxygen delivery as a distractor so candidates are not torn between bronchodilator/steroid pathways and oxygen alone.
- Where acute bronchodilator therapy is appropriate, prefer precise UK-style wording such as “oxygen-driven nebulised salbutamol” or “nebulised salbutamol with oxygen” rather than vague “controlled oxygen therapy” alone.
- Avoid combined “double” treatments in one option (e.g. nebuliser plus steroid plus oxygen in a single line) unless the learning outcome explicitly tests combined acute package management.
- Do not use intramuscular adrenaline (epinephrine) as an asthma distractor unless the stem clearly raises anaphylaxis or other acute allergic features where IM adrenaline is proportionate.

Observation style (when numerical observations are given)
- Observations must follow this order: temperature, pulse, blood pressure, respiratory rate, oxygen saturation.
- If you do not need every vital, include only those that matter—but keep the same relative order (e.g. pulse before blood pressure before respiratory rate before oxygen saturation when several are given).
- Use “pulse”, not “heart rate”, when reporting the pulse.
- Prefer **direct observation phrasing** in one sentence, e.g. **“His temperature is …, pulse …, blood pressure …, respiratory rate … and oxygen saturation …”** (adjust pronoun and punctuation naturally); avoid formulaic wrappers such as **“His observations are:”**, **“Her observations are:”**, **“Observations show”**, **“Observation shows”**, **“vital signs show”**, or **“observations show”**.
- For **respiratory rate**, write **“breaths per minute”**, not **“breaths/min”**.
- Avoid vague severity labels such as “respiratory distress” when you already give numerical observations; prefer objective numbers (respiratory rate, saturations, accessory muscle use, ability to complete sentences).
- Do not add adherence or device-use detail (e.g. spacer technique, compliance) unless it changes which option is correct for the lead-in.
- Avoid vague vital-sign bundles such as **“tachycardic with a pulse”**; state the **pulse** (and other numbers) clearly in **observation order**.
- Observations in **sentences** must be **grammatically complete**: write **“His pulse is 78 bpm”**, **“Her respiratory rate is 18 breaths per minute”**, **“His blood pressure is 120/80 mmHg”** — never **“Her respiratory rate 18 breaths per minute”**, **“His pulse 70 bpm”**, or **“His BP 120/80 mmHg”** without **is**.
- Do **not** write **“Respiratory rate 22 breaths per minute”**, **“Her pulse 110 bpm”**, **“Pulse 92 bpm”**, or **“BP 85/50 mmHg”** in sentence-style text without **is** / **of** — write **“Respiratory rate is 22 breaths per minute”** (or use clean list style below).
- Do **not** mix sentence style and list style in one clause (e.g. **“Her temperature is 36.8°C, pulse 88 bpm, BP 118/72 mmHg, a respiratory rate 22 breaths per minute and oxygen saturation is 96% breathing air”**).
- **Sentence style (good):** **“Her respiratory rate is 22 breaths per minute and oxygen saturation is 96% breathing air.”** **“His pulse is 70 bpm and blood pressure is 120/80 mmHg.”**
- **List style (good):** **“Observations are: temperature 36.8°C, pulse 88 bpm, BP 118/72 mmHg, respiratory rate 22 breaths per minute and oxygen saturation 96% breathing air.”**
- After **examination findings** (**She has …** / **He has …**), start **vitals in a new sentence** (**Her respiratory rate is …**) or use **“, a respiratory rate of …”** — never **“She has wheeze, respiratory rate 18 breaths per minute”**.
- Clean **list-style** observation strings without possessive openers (e.g. **temperature 36.8°C, pulse 72 bpm, BP 120/75 mmHg, respiratory rate 9 breaths per minute and oxygen saturation is 96% breathing air**) are acceptable.

Language style (acute / emergency context)
- Prefer “attends the emergency department” over “arrives at the emergency department”.
- Avoid stock AI lead-ins such as “most appropriate immediate management step”; prefer varied, natural lead-ins such as “What treatment should be given first?”, “What is the most appropriate treatment?”, or “What is the next step in management?” (still align with the Current skill).

Related (oxygen in options)
- If any option mentions oxygen therapy, the stem should already include saturations **on breathing air** or on stated oxygen, as in earlier rules—do not invite oxygen trade-offs without numbers.
- Do not make oxygen escalation the closest distractor unless the correct answer is truly about oxygen delivery.
- Avoid vague subjective phrases such as “visibly distressed” unless you also give objective support (e.g. respiratory rate, saturations, accessory muscle use, inability to complete sentences).

STYLE CONSTRAINTS
- Do not name the university or examination board.
- Do not output markdown outside the JSON requirement below.

OUTPUT
Return valid JSON ONLY with exactly these keys (no markdown fences, no commentary):
title
stem
lead_in
option_a
option_b
option_c
option_d
option_e
correct_answer_letter
correct_answer
justification

The justification must be **concise reviewer-style notes**, usually **about 3–4 sentences** (why the key is best and why major distractors fail for **this** vignette), not tutor-style teaching paragraphs. Avoid meta narrator framing such as **“The vignette presents …”** (with or without “a classic case”); avoid opening with **“Option [letter] is …”**. Prefer direct clinical reasoning (e.g. “Acute pancreatitis is most likely because …”). Do **not** infer **dehydration** or **pre-renal AKI** **only** from **oliguria** or **reduced urine output** without other volume-status cues already stated in the stem. Do **not** rely on **baseline**, **stable**, or **previous creatinine** in the justification unless the **stem** already gives a **prior numeric creatinine** (or an explicit baseline / previous value) that candidates can use. For **antibiotic** prescribing, briefly note that **alternatives** may be required for **allergy** or **local circumstances**, while explaining why the **keyed** drug is best **for this vignette**.

CRITICAL FORMAT RULES:
- Return **one valid JSON object only**.
- **No markdown fences**.
- **No prose before or after** the JSON.
- **No trailing commentary**.
- Include **all required keys** with non-empty values.

Return JSON only. No extra text.
PROMPT;
}
