<?php

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/generator_batch_context.php';
require_once __DIR__ . '/../../prompts/sba_ai_reviewer_prompt.php';
require_once __DIR__ . '/../ai/form_generator_question_validation.php';

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

if ($question_id === '') {
    echo json_encode(['status' => 'error', 'message' => 'Missing question ID.']);
    exit;
}

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

if (!$question) {
    echo json_encode(['status' => 'error', 'message' => 'Question not found.']);
    exit;
}

if (($question['source_type'] ?? '') !== 'generated') {
    echo json_encode(['status' => 'error', 'message' => 'AI review is only available for generated SBA questions.']);
    exit;
}

$question = formGeneratorApplyStyleRepairToQuestionRow($question);

$styleWarnings = [];
$warningsRaw = $_POST['style_warnings'] ?? '';
if (is_string($warningsRaw) && $warningsRaw !== '') {
    $decoded = json_decode($warningsRaw, true);
    if (is_array($decoded)) {
        $styleWarnings = $decoded;
    }
}

if ($styleWarnings === []) {
    $validatorPath = __DIR__ . '/../../validators/style_validator.php';
    if (is_readable($validatorPath)) {
        require_once $validatorPath;
        if (function_exists('validateSbaStyle')) {
            $qStyle = $question;
            $qStyle['_tutor_comments'] = (string) ($question['tutor_comments'] ?? '');
            $qStyle['_current_skill'] = (string) ($question['skill'] ?? '');
            $qStyle['_condition_name'] = (string) ($question['condition_name'] ?? '');
            $batchJobId = generatorParseBatchJobIdFromTags((string) ($question['tags'] ?? ''));
            $qStyle['_batch_prior_questions'] = [];
            if ($batchJobId > 0 && ($question['workspace_id'] ?? '') !== '') {
                $priors = fetchFormGeneratorPriorQuestionsInBatch(
                    $pdo,
                    (string) $question['workspace_id'],
                    $batchJobId
                );
                $qStyle['_batch_prior_questions'] = array_values(array_filter(
                    $priors,
                    static fn ($row) => is_array($row)
                ));
            }
            try {
                $validated = validateSbaStyle($qStyle);
                $styleWarnings = is_array($validated) ? $validated : [];
            } catch (Throwable $e) {
                $styleWarnings = [];
            }
        }
    }
}

$batchSiblings = [];
$batchJobId = generatorParseBatchJobIdFromTags((string) ($question['tags'] ?? ''));
if ($batchJobId > 0 && ($question['workspace_id'] ?? '') !== '') {
    $priors = fetchFormGeneratorPriorQuestionsInBatch(
        $pdo,
        (string) $question['workspace_id'],
        $batchJobId
    );
    foreach ($priors as $row) {
        if (!is_array($row)) {
            continue;
        }
        $batchSiblings[] = [
            'skill' => $row['skill'] ?? '',
            'correct_answer' => $row['correct_answer'] ?? '',
            'lead_in' => $row['lead_in'] ?? '',
            'title' => $row['title'] ?? '',
        ];
    }
}

$prompt = buildSbaAiReviewerPrompt($question, $styleWarnings, $batchSiblings);
$fetch = formGeneratorOpenAiChatJsonQuestion(
    $prompt,
    '',
    0,
    0.35,
    formGeneratorOpenAiSbaReviewModel()
);

if (!$fetch['ok'] || !is_array($fetch['data'])) {
    echo json_encode([
        'status' => 'error',
        'message' => $fetch['error'] !== '' ? $fetch['error'] : 'AI review failed.',
        'raw_response' => $fetch['raw'] ?? '',
    ]);
    exit;
}

$normalized = normalizeSbaAiReviewerResponse($fetch['data']);
if (!$normalized['ok'] || !is_array($normalized['data'])) {
    echo json_encode([
        'status' => 'error',
        'message' => $normalized['error'] !== '' ? $normalized['error'] : 'AI review returned JSON that could not be validated.',
        'raw_response' => $fetch['raw'] ?? '',
    ]);
    exit;
}

echo json_encode([
    'status' => 'success',
    'message' => 'AI review complete.',
    'ai_review' => $normalized['data'],
    'reviewed_at' => gmdate('c'),
]);
