<?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_review.php';

/**
 * @return never
 */
function variantAdvisoryReviewJsonResponse(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 === '') {
    variantAdvisoryReviewJsonResponse([
        'ok' => false,
        'advisory_review' => null,
        'error' => 'missing_question_id',
        'tutor_message' => 'Advisory review unavailable. Tutor review still required.',
        'detail' => 'Missing variant question ID.',
    ], 400);
}

if ($sourceJson === '') {
    variantAdvisoryReviewJsonResponse([
        'ok' => false,
        'advisory_review' => null,
        'error' => 'missing_source',
        'tutor_message' => 'Advisory review unavailable. Tutor review still required.',
        'detail' => 'Missing source question payload.',
    ], 400);
}

$sourceQuestion = json_decode($sourceJson, true);
if (!is_array($sourceQuestion)) {
    variantAdvisoryReviewJsonResponse([
        'ok' => false,
        'advisory_review' => null,
        'error' => 'invalid_source_json',
        'tutor_message' => 'Advisory review unavailable. Tutor review still required.',
        '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) {
    variantAdvisoryReviewJsonResponse([
        'ok' => false,
        'advisory_review' => null,
        'error' => 'variant_not_found',
        'tutor_message' => 'Advisory review unavailable. Tutor review still required.',
        'detail' => 'Variant question not found.',
    ], 404);
}

if (($variant['source_type'] ?? '') !== 'variant') {
    variantAdvisoryReviewJsonResponse([
        'ok' => false,
        'advisory_review' => null,
        'error' => 'not_variant',
        'tutor_message' => 'Advisory review unavailable. Tutor review still required.',
        'detail' => 'Question is not a generated variant.',
    ], 400);
}

try {
    $prompt = buildVariantAdvisoryReviewPrompt($sourceQuestion, $variant);
    $fetch = formGeneratorOpenAiChatJsonQuestion(
        $prompt,
        '',
        0,
        0.2,
        variantOpenAiReviewModel()
    );

    if (!$fetch['ok'] || !is_array($fetch['data'])) {
        $detail = $fetch['error'] !== '' ? $fetch['error'] : 'Review service could not complete.';
        error_log('[review_variant_advisory] OpenAI failure question_id=' . $questionId . ' ' . $detail);
        variantAdvisoryReviewJsonResponse([
            'ok' => false,
            'advisory_review' => null,
            'error' => 'openai_failed',
            'tutor_message' => 'Advisory review unavailable. Tutor review still required.',
            'detail' => $detail,
        ], 502);
    }

    $normalized = normalizeVariantAdvisoryReviewResponse($fetch['data']);
    if (!$normalized['ok'] || !is_array($normalized['data'])) {
        error_log('[review_variant_advisory] Invalid review JSON question_id=' . $questionId . ' '
            . ($normalized['error'] ?? ''));
        variantAdvisoryReviewJsonResponse([
            'ok' => false,
            'advisory_review' => null,
            'error' => 'invalid_review_json',
            'tutor_message' => 'Advisory review unavailable. Tutor review still required.',
            'detail' => $normalized['error'] !== '' ? $normalized['error'] : 'Review JSON could not be validated.',
        ], 502);
    }

    variantAdvisoryReviewJsonResponse([
        'ok' => true,
        'advisory_review' => $normalized['data'],
        'review_phase' => 'pre_repair',
        'error' => '',
        'tutor_message' => '',
        'detail' => '',
    ]);
} catch (Throwable $e) {
    error_log('[review_variant_advisory] Exception question_id=' . $questionId . ' ' . $e->getMessage());
    variantAdvisoryReviewJsonResponse([
        'ok' => false,
        'advisory_review' => null,
        'error' => 'exception',
        'tutor_message' => 'Advisory review unavailable. Tutor review still required.',
        'detail' => 'An unexpected error occurred.',
    ], 500);
}
