<?php

function embedVariantField($value, $maxLen = 12000) {
    $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;
}

/**
 * Format a metadata line for the prompt; empty values are explicitly marked not provided.
 */
function variantPromptMetaLine(string $label, string $value): string
{
    $v = trim($value);

    return '- ' . $label . ': ' . ($v !== '' ? $v : '(not provided — infer from question content if needed)');
}

function buildVariantPrompt(array $sourceQuestion, int $variantNumber): string
{
    $rowNumber = $sourceQuestion['row_number'] ?? '';
    $data = $sourceQuestion['data'] ?? [];

    $questionTitle = embedVariantField($data['Question title'] ?? '');
    $questionText = embedVariantField($data['Question text'] ?? '');
    // Separate spreadsheet columns — never merge Comments into Examiner notes.
    $comments = embedVariantField($data['Comments'] ?? '');
    $examinerNotes = embedVariantField($data['Examiner notes'] ?? '');
    $coreCondition = embedVariantField($data['Core condition'] ?? '');
    $presentation = embedVariantField($data['Presentation'] ?? '');
    $skill = embedVariantField($data['Skill'] ?? '');
    $specialty = embedVariantField($data['Specialty'] ?? '');
    $summativeFormative = embedVariantField($data['Summative/Formative'] ?? '');
    $year = embedVariantField($data['Year'] ?? '');
    $itemType = embedVariantField($data['Type'] ?? 'SBA');
    $stem = embedVariantField($data['Stem'] ?? '');
    $correctAnswer = embedVariantField($data['Correct answer'] ?? '');
    $correctAnswerLetter = embedVariantField($data['Correct answer letter'] ?? '');
    $learningOutcome = embedVariantField(
        $data['Learning outcome'] ?? $data['Learning outcomes'] ?? $data['Learning Outcome'] ?? ''
    );
    $appliedKnowledge = embedVariantField($data['Applied knowledge'] ?? $data['Applied Knowledge'] ?? '');
    $careSetting = embedVariantField($data['Care setting'] ?? $data['Care Setting'] ?? '');
    $justificationSeed = embedVariantField($data['Justification'] ?? $data['justification'] ?? '');

    $seedOptA = embedVariantField($data['Option A'] ?? '', 2000);
    $seedOptB = embedVariantField($data['Option B'] ?? '', 2000);
    $seedOptC = embedVariantField($data['Option C'] ?? '', 2000);
    $seedOptD = embedVariantField($data['Option D'] ?? '', 2000);
    $seedOptE = embedVariantField($data['Option E'] ?? '', 2000);

    $metaBlock = implode("\n", [
        variantPromptMetaLine('Learning focus / skill tested', $skill),
        variantPromptMetaLine('Core condition', $coreCondition),
        variantPromptMetaLine('Presentation', $presentation),
        variantPromptMetaLine('Specialty', $specialty),
        variantPromptMetaLine('Learning outcome(s)', $learningOutcome),
        variantPromptMetaLine('Applied knowledge', $appliedKnowledge),
        variantPromptMetaLine('Care setting', $careSetting),
        variantPromptMetaLine('Assessment type (Summative/Formative)', $summativeFormative),
        variantPromptMetaLine('Learner level / Year', $year),
        variantPromptMetaLine('Question type', $itemType),
    ]);

    $examinerBlock = variantPromptMetaLine('Examiner notes', $examinerNotes);
    $commentsBlock = variantPromptMetaLine('Comments', $comments);
    $justificationBlock = variantPromptMetaLine('Source justification', $justificationSeed);

    return <<<PROMPT
You are writing a VARIANT of an existing Single Best Answer (SBA) item for UK medical school / MLA AKT (MS AKT) use. The source may be a full RISR export or a simpler import (e.g. Microsoft Forms) with only question text, options, correct answer and justification. This is NOT the same task as authoring a question from scratch.

GOAL
Produce ONE new exam-quality variant that is clearly distinct from the seed (new vignette, new wording, reshuffled options, new distractor content) while remaining clinically equivalent to the source item, written in MS AKT style, and suitable for tutor review and editing.

EDUCATIONAL EQUIVALENCE (mandatory)
1. Test the same underlying knowledge point, reasoning step, or misconception as the source question.
2. Preserve the same correct answer **concept** as the seed unless doing so would make the item unsafe or invalid; re-derive correctness from your NEW vignette.
3. Write a genuinely new clinical vignette — not a sentence-by-sentence paraphrase of the seed.
4. Change enough clinical details (presentation cues, timing, context, option wording) to reduce simple pattern recognition, without changing what is being tested.
5. Keep the same approximate difficulty and exam level; if Year or assessment type are not provided, infer level from stem complexity and option discrimination.
6. Keep options plausible, homogeneous for the lead-in, concise, and in sentence case.
7. Ensure exactly one clearly best answer among the five options.
8. Do not make the variant so different that it becomes an unrelated new question.
9. Keep the item clear, internally consistent, and suitable for tutor review (no ambiguous keys or unsupported leaps).

METADATA AND LEARNING OUTCOMES (how to use source fields)
- Use learning outcomes, condition, presentation, specialty, applied knowledge, care setting, skill, year, and other metadata below as **anchors when they are provided**.
- **Do not require** learning outcomes, tags, or formal metadata to be present. A valid source may include only stem/question text, options, correct answer and justification.
- If any field below is marked **(not provided — infer from question content if needed)**, do **not** treat its absence as an error. Infer the tested knowledge point, clinical concept, task type (diagnosis, investigation, management, etc.) and reasoning step from the **stem, lead-in (if separable), options, correct answer and justification**.
- When metadata is missing, treat the **correct answer** and **justification** (if provided) as the **strongest clues** to the intended learning point, then cross-check against the stem and distractors.
- **Do not invent** formal learning outcomes, curriculum codes, or tags in your output. Your JSON contains only question fields (title, stem, lead_in, options, correct answer, justification) — do not add extra metadata keys.
- Do not fabricate unsupported metadata in prose inside the stem or justification (e.g. do not cite a named learning outcome that was not in the source unless examiner notes require it).

SOURCE METADATA (use when provided; otherwise infer as above)
{$metaBlock}
{$examinerBlock}
{$commentsBlock}
{$justificationBlock}

Preserve the intent of Examiner notes and Comments when provided; do not copy long text verbatim into the variant.

SEED CONTENT (reference only — infer learning objective and difficulty; do NOT copy sentences or distinctive phrases)
- Uploaded row number: {$rowNumber}
- Variant index for this source row: {$variantNumber}
- Question title: {$questionTitle}
- Question text (full stem / vignette from upload): {$questionText}
- Optional separate stem field if present in file: {$stem}
- Original correct answer letter (concept only): {$correctAnswerLetter}
- Original correct answer label text (concept only): {$correctAnswer}
- Prior options A–E (rewrite entirely; use only to infer distractor families to avoid repeating): A: {$seedOptA} | B: {$seedOptB} | C: {$seedOptC} | D: {$seedOptD} | E: {$seedOptE}

WHAT YOU MUST CHANGE (variant-specific)
- Write a NEW clinical scenario and NEW lead-in; no substantial reuse of seed wording.
- Alter option order where logical; assign correct_answer_letter to the letter that truly fits your NEW options.
- Replace distractors with NEW plausible wrong answers (different wording and, where appropriate, different error mechanisms) while staying homogeneous for the inferred or stated task type and lead-in.

MS AKT / MLA AKT STYLE REQUIREMENTS (apply to stem, lead-in, options, and justification)
**Stem**
- Present tense, third person.
- Start most clinical stems with age and gender, e.g. “A 45 year old woman…” (do not hyphenate age: “45 year old”, not “45-year-old”).
- Do not use patient names.
- Give the presenting symptom or problem in the first sentence.
- Aim for a concise stem, usually about 30–100 words unless the source clearly requires more.
- Omit extraneous details that do not help discriminate between the options.
- Simple wording: “start” not “commence”; “stop” not “discontinue”.
- Avoid “presents with” and “complains of”; prefer “has”.
- Avoid “known to have”, “diagnosed with”, and “with a history of”; prefer direct statements, e.g. “She has type 2 diabetes mellitus”.
- Avoid “On examination”.
- If observations are given, use this order: temperature, pulse, BP, respiratory rate, oxygen saturation.
- Use “pulse” not “pulse rate”.
- For room-air saturations use “oxygen saturation is 98% breathing air”, not “on room air” or “on air”.
- **Observation grammar (critical):** Do **not** write clipped possessive vitals such as “His pulse 72 bpm”, “Her BP 135/85 mmHg”, or “His blood pressure 120/75 mmHg”.
- Use **either** full possessive sentences with “is”/“are” (e.g. “His pulse is 72 bpm, blood pressure is 120/75 mmHg, respiratory rate is 9 breaths per minute and oxygen saturation is 80% breathing air”) **or** a complete list-style phrase without His/Her leading the vital list (e.g. “temperature 36.8°C, pulse 72 bpm, BP 120/75 mmHg…”). Do **not** mix the two styles.

**Lead-in**
- Use “What?” for most lead-ins unless “Which?” is clearly justified.
- Avoid negative lead-ins such as “least likely”.
- The lead-in must pass both cover tests:
  a) the candidate should be able to infer the answer without seeing the options;
  b) the candidate should not be able to answer without reading the stem.

**Options**
- Exactly five options (A–E in your JSON as option_a … option_e).
- Plausible, realistic, homogeneous, concise, sentence case.
- List in alphabetical, numerical, or the most logical order where possible.
- British spelling and grammar throughout.
- Generic medicine names where possible; UK-consistent terminology.
- Lower case for clinical specialties, hospital departments, generic drug names and conditions unless a proper noun is required.
- Eponyms without possessive apostrophes, e.g. “Down syndrome” not “Down’s syndrome”.
- Inclusive language; avoid unnecessary demographic details unless clinically relevant.
- Avoid skin colour descriptors that only work for lighter skin tones unless skin colour is specifically relevant to the item.

YOU MUST NOT
- Produce a superficial paraphrase of the seed.
- Copy distinctive phrases from the original where avoidable.
- Introduce clinical facts, results, or findings not supported by your stem.
- Change the correct answer concept away from the seed (unless safety would require it — then stay as close as safely possible and keep one best answer).
- Create more than one defensibly correct option.
- Use American spelling.
- Refuse, degrade, or hollow out the variant **just because** learning outcomes or tags are missing from the upload.
- Output anything other than the JSON object below (no markdown fences, no commentary).

OUTPUT FORMAT
Return valid JSON only. No markdown. No text outside JSON.

{
  "title": "string",
  "stem": "string",
  "lead_in": "string",
  "option_a": "string",
  "option_b": "string",
  "option_c": "string",
  "option_d": "string",
  "option_e": "string",
  "correct_answer_letter": "A, B, C, D, or E",
  "correct_answer": "string",
  "justification": "string"
}

RULES
- Exactly five options; exactly one best answer.
- correct_answer must match the text of the option given by correct_answer_letter.
- Justification: briefly why the best option wins and why major distractors fail in THIS vignette only; do not reference options that are not in your final set.
- Do not output anything except the JSON object.

Return JSON only.
PROMPT;
}
