<?php
/**
 * Regenerate ONE question bank item in place with AI.
 *
 * Keeps the row id (so it stays in any paper that uses it) and its type/subject/
 * class/topic; replaces the content with a fresh AI-generated version through the
 * unified RBCAIEngine. Supports every question type (mcq, true_false, fill_blank,
 * theory, matching, comprehension) and diagrams.
 */
declare(strict_types=1);
require_once __DIR__ . '/_json_guard.php';
session_start();
require_once '../../config.php';
require_once dirname(__DIR__) . '/includes/claude_api.php';                 // repairAndParseJSON(), callAI()
if (!class_exists('RBCAIEngine')) {
    require_once dirname(__DIR__, 2) . '/ai/provider_engine.php';
}
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$conn = getDBConnection();
if (!$conn instanceof mysqli) {
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

$id = (int) ($_POST['id'] ?? 0);
if ($id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid question id']);
    exit;
}

$stmt = $conn->prepare("SELECT eq.*, s.subject_name FROM exam_questions eq LEFT JOIN subjects s ON s.id = eq.subject_id WHERE eq.id = ? LIMIT 1");
$stmt->bind_param('i', $id);
$stmt->execute();
$q = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$q) {
    echo json_encode(['success' => false, 'message' => 'Question not found']);
    exit;
}

$type        = (string) ($q['question_type'] ?? 'mcq');
$subjectName = (string) ($q['subject_name'] ?? 'the subject');
$className   = (string) ($q['class_name'] ?? '');
$difficulty  = (string) ($q['difficulty'] ?? 'medium');
$topic       = trim((string) ($q['chunk_topic'] ?? '')) ?: trim((string) ($q['question'] ?? '')) ?: $subjectName;
$prev        = trim((string) ($q['question'] ?? ''));

$system = <<<SYS
You are an examination officer for the Ghana Education Service (GES).
Regenerate ONE fresh, curriculum-accurate exam question. Return a JSON ARRAY containing
EXACTLY ONE question object with these fields:
  type           : "{$type}" (keep exactly this type)
  question       : string
  option_a..option_d : strings (mcq only; "" otherwise)
  correct_answer : mcq "A"-"D"; true_false "True"/"False"; "" otherwise
  model_answer   : fill_blank = exact accepted answer; theory = concise model answer; mcq = one short reason; "" if not applicable
  marking_guide  : array of strings for theory (mark breakdown); [] otherwise
  marks          : integer
  diagram_required: boolean, diagram_type: string, diagram_spec: object|null
  extra_data     : object|null —
                   matching: {"pairs":[{"left":"..","right":".."}, ...]} (4-6 pairs)
                   comprehension: {"passage":"..","questions":[{"text":"..","marks":n,"model_answer":".."}, ...]}
Make it clearly DIFFERENT from the previous version, suitable for the class level.
Return ONLY the JSON array — no markdown, no commentary.
SYS;

$user = "SUBJECT: {$subjectName}\nCLASS LEVEL: {$className}\nTOPIC: {$topic}\nDIFFICULTY: {$difficulty}\nQUESTION TYPE: {$type}\n\nPREVIOUS QUESTION (write a different one on the same topic and type):\n{$prev}";

// Generate — unified engine first, legacy cascade as fallback.
$content = '';
if (class_exists('RBCAIEngine')) {
    $r = RBCAIEngine::generate($user, $system, 2000, false);
    if (!empty($r['success'])) {
        $content = (string) $r['content'];
    }
}
if ($content === '') {
    $ai = callAI($system, $user, 2000);
    if (!empty($ai['error'])) {
        echo json_encode(['success' => false, 'message' => 'AI regeneration failed: ' . $ai['error']]);
        exit;
    }
    $content = (string) $ai['result'];
}

$parsed = repairAndParseJSON($content);
$new = is_array($parsed) ? (isset($parsed[0]) && is_array($parsed[0]) ? $parsed[0] : $parsed) : null;
if (!is_array($new) || trim((string) ($new['question'] ?? '')) === '') {
    echo json_encode(['success' => false, 'message' => 'AI returned an invalid question. Please try again.']);
    exit;
}

// ── Map fields ─────────────────────────────────────────────────────────────
$question      = trim((string) ($new['question'] ?? ''));
$optionA       = (string) ($new['option_a'] ?? '');
$optionB       = (string) ($new['option_b'] ?? '');
$optionC       = (string) ($new['option_c'] ?? '');
$optionD       = (string) ($new['option_d'] ?? '');
$correctAnswer = (string) ($new['correct_answer'] ?? '');
$modelAnswer   = trim((string) ($new['model_answer'] ?? ''));
$markingGuide  = '';
if (!empty($new['marking_guide'])) {
    $markingGuide = is_array($new['marking_guide'])
        ? implode("\n", array_filter(array_map(static fn($p) => trim((string) $p), $new['marking_guide'])))
        : (string) $new['marking_guide'];
}
$marks       = max(1, (int) ($new['marks'] ?? ($q['marks'] ?? 1)));
$diagramReq  = !empty($new['diagram_required']) ? 1 : 0;
$diagramType = (string) ($new['diagram_type'] ?? '');
$diagramSpec = !empty($new['diagram_spec']) && is_array($new['diagram_spec']) ? json_encode($new['diagram_spec'], JSON_UNESCAPED_UNICODE) : null;
$extraData   = isset($new['extra_data']) && is_array($new['extra_data']) ? json_encode($new['extra_data'], JSON_UNESCAPED_UNICODE) : null;

// Keep marks consistent for the structural types.
if ($type === 'comprehension' && isset($new['extra_data']['questions']) && is_array($new['extra_data']['questions'])) {
    $sub = array_sum(array_map(static fn($s) => max(1, (int) ($s['marks'] ?? 1)), $new['extra_data']['questions']));
    if ($sub > 0) { $marks = $sub; }
} elseif ($type === 'matching' && isset($new['extra_data']['pairs']) && is_array($new['extra_data']['pairs'])) {
    $marks = max($marks, count($new['extra_data']['pairs']));
}

$up = $conn->prepare(
    "UPDATE exam_questions
        SET question=?, option_a=?, option_b=?, option_c=?, option_d=?,
            correct_answer=?, model_answer=?, marking_guide=?, marks=?,
            diagram_required=?, diagram_type=?, diagram_spec=?, extra_data=?,
            refined=0
      WHERE id=?"
);
$up->bind_param(
    'ssssssssiisssi',
    $question, $optionA, $optionB, $optionC, $optionD,
    $correctAnswer, $modelAnswer, $markingGuide, $marks,
    $diagramReq, $diagramType, $diagramSpec, $extraData,
    $id
);
$ok = $up->execute();
$up->close();

if (!$ok) {
    echo json_encode(['success' => false, 'message' => 'Could not save the regenerated question.']);
    exit;
}

echo json_encode(['success' => true, 'message' => 'Question regenerated.', 'id' => $id]);
