<?php

declare(strict_types=1);

require_once __DIR__ . '/prompt_variant.php';
require_once __DIR__ . '/prompt_variant_review.php';

/**
 * Variant-only post-repair reviewer model (mirrors main SBA 5.1; read-only).
 */
function variantOpenAiPostRepairReviewModel(): string
{
    if (defined('OPENAI_VARIANT_POST_REPAIR_REVIEW_MODEL')) {
        $m = trim((string) OPENAI_VARIANT_POST_REPAIR_REVIEW_MODEL);
        if ($m !== '') {
            return $m;
        }
    }

    return variantOpenAiReviewModel();
}

/**
 * @param array<string, mixed> $sourceQuestion
 * @param array<string, mixed> $variant DB row (repaired Draft)
 * @param array<string, mixed> $context optional change_log, advisory_review
 */
function buildVariantPostRepairReviewPrompt(
    array $sourceQuestion,
    array $variant,
    array $context = []
): string {
    $data = is_array($sourceQuestion['data'] ?? null) ? $sourceQuestion['data'] : [];
    $rowNumber = (string) ($sourceQuestion['row_number'] ?? '');

    $questionTitle = embedVariantField($data['Question title'] ?? '');
    $questionText = embedVariantField($data['Question text'] ?? '');
    $stemSeed = embedVariantField($data['Stem'] ?? '');
    $correctAnswer = embedVariantField($data['Correct answer'] ?? '');
    $correctAnswerLetter = embedVariantField($data['Correct answer letter'] ?? '');
    $justificationSeed = embedVariantField($data['Justification'] ?? $data['justification'] ?? '');
    $learningOutcome = embedVariantField(
        $data['Learning outcome'] ?? $data['Learning outcomes'] ?? $data['Learning Outcome'] ?? ''
    );

    $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 outcome(s)', $learningOutcome),
        variantPromptMetaLine('Core condition', embedVariantField($data['Core condition'] ?? '')),
        variantPromptMetaLine('Skill', embedVariantField($data['Skill'] ?? '')),
    ]);

    $vTitle = embedVariantField($variant['title'] ?? '');
    $vStem = embedVariantField($variant['stem'] ?? '');
    $vLeadIn = embedVariantField($variant['lead_in'] ?? '');
    $vJust = embedVariantField($variant['justification'] ?? '');
    $vLetter = embedVariantField($variant['correct_answer_letter'] ?? '');
    $vAnswer = embedVariantField($variant['correct_answer'] ?? '');
    $vA = embedVariantField($variant['option_a'] ?? '', 2000);
    $vB = embedVariantField($variant['option_b'] ?? '', 2000);
    $vC = embedVariantField($variant['option_c'] ?? '', 2000);
    $vD = embedVariantField($variant['option_d'] ?? '', 2000);
    $vE = embedVariantField($variant['option_e'] ?? '', 2000);

    $contextJson = json_encode($context, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    if ($contextJson === false) {
        $contextJson = '{}';
    }

    return <<<PROMPT
You are an expert UK medical school item reviewer performing a **post-repair tutor review** of a **generated variant** that has already passed automatic repair.

**CRITICAL — ADVISORY SUGGESTIONS ONLY**
- You are reviewing the **final repaired Draft** shown below, compared with the **original source** question.
- Provide **structured suggestions** for a human tutor. You must **not** rewrite or replace the question in your output.
- You must **not** approve the item for export. **do_not_auto_apply** and **tutor_review_required** must be true.
- Do **not** invent formal learning outcomes, curriculum codes, or tags.
- Return **valid JSON only** (no markdown fences).

**MISSING METADATA**
- If learning outcomes are absent, infer the intended learning point from source and repaired content.
- Use source **correct answer** and **justification** as anchors for answer concept.

**COMPARE**
1. **SOURCE** (original uploaded item) — educational anchor and formal answer concept.
2. **REPAIRED DRAFT** (current variant after automatic repair) — what the tutor will see.
3. Optional **repair context** (pre-repair review / change log) — for awareness only; judge the **repaired** text.

**ASSESS**

1. **Clinical equivalence** — Same learning point / reasoning? Scenario change that alters intended reasoning?
2. **Correct answer concept** — Same formal concept as source? Diagnosis/drug/investigation/management preserved, not replaced by symptom/sign/vague phrase? (e.g. source “Laryngitis” must not become “Hoarseness of voice” as keyed answer.)
3. **Guideline-sensitive details** — Age, sex, pregnancy, comorbidities, renal function, meds, timing, severity, setting: any change that alters the answer pathway? (e.g. hypertension item needing age ≥55 for amlodipine must stay ≥55.)
4. **MLA AKT / MS AKT style** — Present tense, third person; age/gender at start; no patient names; “What?” lead-ins; concise stem; five homogeneous concise options; British spelling; observations: temperature, pulse, BP, respiratory rate, oxygen saturation; “respiratory rate N breaths per minute”; “pulse N bpm”; “oxygen saturation is N% breathing air”; units g/L, fL, mmol/L, µmol/L, × 10⁹/L.
5. **Single best answer** — One clearly best answer? Distractors plausible but clearly weaker? Too close? All options stem-supported?
6. **Clinical realism** — Plausible findings for the setting? No unsupported assumptions or impossible direct examination claims?

**SUGGESTIONS**
- Provide specific, actionable **suggestions** with **area**, **current_text** (from repaired draft), **suggested_text**, **reason**, **priority** (low | medium | high).
- **area** must be one of: stem | lead_in | option | correct_answer | justification | tags | general
- Maximum **12** suggestions; omit empty/low-value items.
- Do not suggest auto-applying edits.

**post_repair_quality**
- **good** — Usable with no or trivial tutor edits.
- **minor_edit_needed** — Small style/wording fixes.
- **major_edit_needed** — Significant clinical, concept, or option issues remain.
- **regenerate** — Fundamental problems; tutor should consider regenerating.

**SOURCE (row {$rowNumber})**
{$metaBlock}
- Title: {$questionTitle}
- Question text: {$questionText}
- Stem field: {$stemSeed}
- Source correct answer: {$correctAnswerLetter} — {$correctAnswer}
- Options: A: {$seedOptA} | B: {$seedOptB} | C: {$seedOptC} | D: {$seedOptD} | E: {$seedOptE}
- Source justification: {$justificationSeed}

**REPAIRED DRAFT (review this)**
- Title: {$vTitle}
- Stem: {$vStem}
- Lead-in: {$vLeadIn}
- Options: A: {$vA} | B: {$vB} | C: {$vC} | D: {$vD} | E: {$vE}
- Correct answer: {$vLetter} — {$vAnswer}
- Justification: {$vJust}

**REPAIR CONTEXT (optional)**
{$contextJson}

OUTPUT — return this JSON object only:

{
  "post_repair_quality": "good | minor_edit_needed | major_edit_needed | regenerate",
  "clinical_equivalence": "pass | concern | unclear",
  "correct_answer_concept": "pass | concern | unclear",
  "guideline_sensitive_details": "pass | concern | unclear",
  "mla_style": "pass | minor_issues | major_issues",
  "single_best_answer": "pass | concern | unclear",
  "clinical_realism": "pass | concern | unclear",
  "summary": "string",
  "suggestions": [
    {
      "area": "stem | lead_in | option | correct_answer | justification | tags | general",
      "current_text": "string",
      "suggested_text": "string",
      "reason": "string",
      "priority": "low | medium | high"
    }
  ],
  "do_not_auto_apply": true,
  "tutor_review_required": true
}
PROMPT;
}

/**
 * @param array<string, mixed> $raw
 * @return array{ok: bool, data: ?array<string, mixed>, error: string}
 */
function normalizeVariantPostRepairReviewResponse(array $raw): array
{
    $quality = ['good', 'minor_edit_needed', 'major_edit_needed', 'regenerate'];
    $ternary = ['pass', 'concern', 'unclear'];
    $style = ['pass', 'minor_issues', 'major_issues'];
    $priority = ['low', 'medium', 'high'];
    $areas = ['stem', 'lead_in', 'option', 'correct_answer', 'justification', 'tags', 'general'];

    $pick = static function (array $allowed, $value, string $default) {
        $v = strtolower(trim((string) $value));

        return in_array($v, $allowed, true) ? $v : $default;
    };

    $summary = trim((string) ($raw['summary'] ?? ''));
    if ($summary === '') {
        return ['ok' => false, 'data' => null, 'error' => 'Post-repair reviewer JSON missing summary.'];
    }

    $suggestions = [];
    if (isset($raw['suggestions']) && is_array($raw['suggestions'])) {
        foreach ($raw['suggestions'] as $item) {
            if (!is_array($item)) {
                continue;
            }
            $area = $pick($areas, $item['area'] ?? '', 'general');
            $current = trim((string) ($item['current_text'] ?? ''));
            $suggested = trim((string) ($item['suggested_text'] ?? ''));
            $reason = trim((string) ($item['reason'] ?? ''));
            if ($reason === '' && $suggested === '' && $current === '') {
                continue;
            }
            $suggestions[] = [
                'area' => $area,
                'current_text' => $current,
                'suggested_text' => $suggested,
                'reason' => $reason,
                'priority' => $pick($priority, $item['priority'] ?? '', 'medium'),
            ];
            if (count($suggestions) >= 12) {
                break;
            }
        }
    }

    $postQuality = $pick($quality, $raw['post_repair_quality'] ?? '', 'minor_edit_needed');

    if (
        ($raw['correct_answer_concept'] ?? '') === 'concern'
        || ($raw['guideline_sensitive_details'] ?? '') === 'concern'
        || ($raw['clinical_equivalence'] ?? '') === 'concern'
    ) {
        if ($postQuality === 'good') {
            $postQuality = 'minor_edit_needed';
        }
    }
    if (($raw['mla_style'] ?? '') === 'major_issues' || ($raw['single_best_answer'] ?? '') === 'concern') {
        if ($postQuality === 'good') {
            $postQuality = 'major_edit_needed';
        }
    }

    $out = [
        'post_repair_quality' => $postQuality,
        'clinical_equivalence' => $pick($ternary, $raw['clinical_equivalence'] ?? '', 'unclear'),
        'correct_answer_concept' => $pick($ternary, $raw['correct_answer_concept'] ?? '', 'unclear'),
        'guideline_sensitive_details' => $pick($ternary, $raw['guideline_sensitive_details'] ?? '', 'unclear'),
        'mla_style' => $pick($style, $raw['mla_style'] ?? '', 'minor_issues'),
        'single_best_answer' => $pick($ternary, $raw['single_best_answer'] ?? '', 'unclear'),
        'clinical_realism' => $pick($ternary, $raw['clinical_realism'] ?? '', 'unclear'),
        'summary' => $summary,
        'suggestions' => $suggestions,
        'do_not_auto_apply' => true,
        'tutor_review_required' => true,
    ];

    return ['ok' => true, 'data' => $out, 'error' => ''];
}
