<?php
declare(strict_types=1);

/**
 * Question Refiner — EduTrack AI Exam Generator
 *
 * Passes generated questions through a secondary AI provider acting as
 * a senior exam moderator.  Available on Growth and Premium plans only.
 */

require_once __DIR__ . '/../includes/claude_api.php';

/**
 * Review and correct a set of generated questions using a second AI provider.
 *
 * @param array  $questions    Raw question array from generateChunkQuestions()
 * @param string $subjectName
 * @param string $className
 * @param string $difficulty
 * @param string $usedEngine  Engine that generated the questions (so we pick a different one)
 * @return array{questions:array,engine:string,refined:bool}
 */
function refineQuestions(
    array  $questions,
    string $subjectName,
    string $className,
    string $difficulty,
    string $usedEngine
): array {
    if (empty($questions)) {
        return ['questions' => $questions, 'engine' => '', 'refined' => false];
    }

    $system = <<<SYSTEM
You are a senior examination moderator for the Ghana Education Service (GES).
A junior exam officer has prepared the questions below. Your job is to review
and correct them in place — do NOT remove or add questions.

CHECK EACH QUESTION FOR:
1. Clarity — is the question unambiguous and grammatically correct?
2. MCQ distractors — exactly ONE option must be correct; wrong options must be
   plausible (reflecting common misconceptions, not obvious nonsense).
3. Difficulty alignment — appropriate for the stated class level and difficulty.
4. Fill-in-the-blank — blank must target a key term, formula, or fact — not a trivial word.
5. Theory questions — must require demonstration of knowledge, not just recall of a single fact.
6. Marks — MCQ=1, Fill=1-2, Theory=3-10. Adjust if wrong.
7. Cultural bias or trick phrasing — fix or reword.

CORRECTIONS:
- Fix issues directly in the question fields.
- Add "moderation_note": "brief explanation" to any question you changed.
- Leave unchanged questions as-is (no moderation_note needed).

OUTPUT: Return ONLY the corrected JSON array. No markdown, no explanation.
SYSTEM;

    $payload = json_encode($questions, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    $user = "SUBJECT: {$subjectName}\nCLASS: {$className}\nDIFFICULTY: {$difficulty}\n\n"
          . "QUESTIONS TO MODERATE:\n{$payload}";

    // Prefer a different engine than the one used for generation
    $order = array_values(array_filter(['claude', 'groq', 'gemini'], fn($e) => $e !== $usedEngine));
    $order[] = $usedEngine; // last-resort fallback to same engine

    foreach ($order as $engine) {
        try {
            $raw = match($engine) {
                'claude' => callClaude($system, $user, 8192),
                'groq'   => callGroq($system, $user, 8192),
                'gemini' => callGemini($system, $user, 8192),
                default  => throw new Exception("Unknown engine: {$engine}"),
            };

            if (empty(trim($raw))) {
                throw new Exception('Empty response');
            }

            $parsed = repairAndParseJSON($raw);
            if (is_array($parsed) && count($parsed) > 0) {
                error_log("[EduTrack Refiner] Success — engine: {$engine}, questions: " . count($parsed));
                return ['questions' => $parsed, 'engine' => $engine, 'refined' => true];
            }

            throw new Exception('Could not parse refined JSON');

        } catch (Exception $e) {
            error_log("[EduTrack Refiner] {$engine} failed: " . $e->getMessage());
        }
    }

    // All engines failed — return originals unmodified
    error_log('[EduTrack Refiner] All engines failed — returning unrefined questions');
    return ['questions' => $questions, 'engine' => '', 'refined' => false];
}
