<?php

declare(strict_types=1);

ini_set('display_errors', '0');

header('Content-Type: application/json');

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../ai/form_generator_retry.php';
require_once __DIR__ . '/../ai/prompt_variant_post_repair_review.php';

/**
 * @return never
 */
function variantPostRepairReviewJsonResponse(array $payload, int $httpCode = 200): void
{
    http_response_code($httpCode);
    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
}

$questionId = trim((string) ($_POST['question_id'] ?? ''));
$sourceJson = (string) ($_POST['source_question_json'] ?? '');

if ($questionId === '') {
    variantPostRepairReviewJsonResponse([
        'ok' => false,
        'post_repair_review' => null,
        'error' => 'missing_question_id',
        'tutor_message' => 'Post-repair reviewer unavailable.',
        'detail' => 'Missing variant question ID.',
    ], 400);
}

if ($sourceJson === '') {
    variantPostRepairReviewJsonResponse([
        'ok' => false,
        'post_repair_review' => null,
        'error' => 'missing_source',
        'tutor_message' => 'Post-repair reviewer unavailable.',
        'detail' => 'Missing source question payload.',
    ], 400);
}

$sourceQuestion = json_decode($sourceJson, true);
if (!is_array($sourceQuestion)) {
    variantPostRepairReviewJsonResponse([
        'ok' => false,
        'post_repair_review' => null,
        'error' => 'invalid_source_json',
        'tutor_message' => 'Post-repair reviewer unavailable.',
        'detail' => 'Source question JSON is invalid.',
    ], 400);
}

$sql = 'SELECT * FROM questions WHERE id = :question_id LIMIT 1';
$stmt = $pdo->prepare($sql);
$stmt->execute(['question_id' => $questionId]);
$variant = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$variant) {
    variantPostRepairReviewJsonResponse([
        'ok' => false,
        'post_repair_review' => null,
        'error' => 'variant_not_found',
        'tutor_message' => 'Post-repair reviewer unavailable.',
        'detail' => 'Variant question not found.',
    ], 404);
}

if (($variant['source_type'] ?? '') !== 'variant') {
    variantPostRepairReviewJsonResponse([
        'ok' => false,
        'post_repair_review' => null,
        'error' => 'not_variant',
        'tutor_message' => 'Post-repair reviewer unavailable.',
        'detail' => 'Question is not a generated variant.',
    ], 400);
}

$context = [];
$changeLogRaw = (string) ($_POST['change_log_json'] ?? '');
if ($changeLogRaw !== '') {
    $decoded = json_decode($changeLogRaw, true);
    if (is_array($decoded)) {
        $context['change_log'] = $decoded;
    }
}
$advisoryRaw = (string) ($_POST['advisory_review_json'] ?? '');
if ($advisoryRaw !== '') {
    $decoded = json_decode($advisoryRaw, true);
    if (is_array($decoded)) {
        $context['pre_repair_advisory_review'] = $decoded;
    }
}

try {
    $prompt = buildVariantPostRepairReviewPrompt($sourceQuestion, $variant, $context);
    $fetch = formGeneratorOpenAiChatJsonQuestion(
        $prompt,
        '',
        0,
        0.2,
        variantOpenAiPostRepairReviewModel()
    );

    if (!$fetch['ok'] || !is_array($fetch['data'])) {
        $detail = $fetch['error'] !== '' ? $fetch['error'] : 'Review service could not complete.';
        error_log('[review_repaired_variant] OpenAI failure question_id=' . $questionId . ' ' . $detail);
        variantPostRepairReviewJsonResponse([
            'ok' => false,
            'post_repair_review' => null,
            'error' => 'openai_failed',
            'tutor_message' => 'Post-repair reviewer unavailable.',
            'detail' => $detail,
        ], 502);
    }

    $normalized = normalizeVariantPostRepairReviewResponse($fetch['data']);
    if (!$normalized['ok'] || !is_array($normalized['data'])) {
        error_log('[review_repaired_variant] Invalid JSON question_id=' . $questionId . ' '
            . ($normalized['error'] ?? ''));
        variantPostRepairReviewJsonResponse([
            'ok' => false,
            'post_repair_review' => null,
            'error' => 'invalid_review_json',
            'tutor_message' => 'Post-repair reviewer unavailable.',
            'detail' => $normalized['error'] !== '' ? $normalized['error'] : 'Review JSON could not be validated.',
        ], 502);
    }

    variantPostRepairReviewJsonResponse([
        'ok' => true,
        'post_repair_review' => $normalized['data'],
        'review_phase' => 'post_repair',
        'error' => '',
        'tutor_message' => '',
        'detail' => '',
    ]);
} catch (Throwable $e) {
    error_log('[review_repaired_variant] Exception question_id=' . $questionId . ' ' . $e->getMessage());
    variantPostRepairReviewJsonResponse([
        'ok' => false,
        'post_repair_review' => null,
        'error' => 'exception',
        'tutor_message' => 'Post-repair reviewer unavailable.',
        'detail' => 'An unexpected error occurred.',
    ], 500);
}
