<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../ai/prompt_variant.php';
require_once __DIR__ . '/../ai/variant_stem_observation_grammar.php';

$job_id = $_POST['job_id'] ?? '';

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

$sql = "SELECT * FROM generation_jobs WHERE id = :job_id LIMIT 1";
$stmt = $pdo->prepare($sql);
$stmt->execute(['job_id' => $job_id]);
$job = $stmt->fetch(PDO::FETCH_ASSOC);

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

if ((int) $job['questions_completed'] >= (int) $job['num_questions']) {
    echo json_encode([
        'status' => 'complete',
        'message' => 'All variants already generated.'
    ]);
    exit;
}

$jobPayload = json_decode($job['learning_outcome'], true);

if (!is_array($jobPayload)) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Variant job payload is invalid.'
    ]);
    exit;
}

if (($jobPayload['job_type'] ?? '') !== 'variant') {
    echo json_encode([
        'status' => 'error',
        'message' => 'This job is not a variant generation job.'
    ]);
    exit;
}

$variantsPerQuestion = isset($jobPayload['variants_per_question']) ? (int) $jobPayload['variants_per_question'] : 0;
$selectedQuestions = $jobPayload['selected_questions'] ?? [];

if ($variantsPerQuestion < 1 || $variantsPerQuestion > 2) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid variants_per_question value in job payload.'
    ]);
    exit;
}

if (!is_array($selectedQuestions) || count($selectedQuestions) === 0) {
    echo json_encode([
        'status' => 'error',
        'message' => 'No selected questions found in job payload.'
    ]);
    exit;
}

$currentIndex = (int) $job['questions_completed'];
$sourceQuestionIndex = (int) floor($currentIndex / $variantsPerQuestion);
$variantNumber = ($currentIndex % $variantsPerQuestion) + 1;

if (!isset($selectedQuestions[$sourceQuestionIndex])) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Could not find the source question for the next variant.'
    ]);
    exit;
}

$sourceQuestion = $selectedQuestions[$sourceQuestionIndex];
$sourceRowNumber = $sourceQuestion['row_number'] ?? null;
$sourceData = $sourceQuestion['data'] ?? [];

if (empty($sourceRowNumber) || !is_array($sourceData)) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Source question data is incomplete.'
    ]);
    exit;
}

$prompt = buildVariantPrompt($sourceQuestion, $variantNumber);

$url = "https://api.openai.com/v1/chat/completions";

$requestData = [
    "model" => "gpt-4o-mini",
    "messages" => [
        [
            "role" => "user",
            "content" => $prompt
        ]
    ],
    "temperature" => 0.7
];

$headers = [
    "Content-Type: application/json",
    "Authorization: Bearer " . OPENAI_API_KEY
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));

$response = curl_exec($ch);

if ($response === false) {
    $curlError = curl_error($ch);
    curl_close($ch);

    echo json_encode([
        'status' => 'error',
        'message' => 'OpenAI request failed: ' . $curlError
    ]);
    exit;
}

curl_close($ch);

$response_data = json_decode($response, true);

if (!is_array($response_data)) {
    echo json_encode([
        'status' => 'error',
        'message' => 'OpenAI response was not valid JSON.',
        'raw_response' => $response
    ]);
    exit;
}

if (!isset($response_data['choices'][0]['message']['content'])) {
    echo json_encode([
        'status' => 'error',
        'message' => 'OpenAI response did not contain message content.',
        'raw_response' => $response_data
    ]);
    exit;
}

$content = $response_data['choices'][0]['message']['content'];
$question_data = json_decode($content, true);

if (!is_array($question_data)) {
    echo json_encode([
        'status' => 'error',
        'message' => 'AI did not return valid JSON.',
        'raw_response' => $content
    ]);
    exit;
}

$title = $question_data['title'] ?? ('Variant of row ' . $sourceRowNumber . ' - ' . $variantNumber);
$stemNorm = variantNormalizeStemObservationGrammar(trim((string) ($question_data['stem'] ?? '')));
$stem = $stemNorm['stem'];
$lead_in = $question_data['lead_in'] ?? '';
$option_a = $question_data['option_a'] ?? '';
$option_b = $question_data['option_b'] ?? '';
$option_c = $question_data['option_c'] ?? '';
$option_d = $question_data['option_d'] ?? '';
$option_e = $question_data['option_e'] ?? '';
$correct_answer_letter = strtoupper(trim($question_data['correct_answer_letter'] ?? ''));
$correct_answer = '';
$answer_options_by_letter = [
    'A' => $option_a,
    'B' => $option_b,
    'C' => $option_c,
    'D' => $option_d,
    'E' => $option_e
];
if (isset($answer_options_by_letter[$correct_answer_letter])) {
    $correct_answer = $answer_options_by_letter[$correct_answer_letter];
}
$justification = $question_data['justification'] ?? '';

$specialty = $sourceData['Specialty'] ?? '';
$conditionName = $sourceData['Core condition'] ?? '';
$presentation = $sourceData['Presentation'] ?? '';
$skill = $sourceData['Skill'] ?? '';
$summativeFormative = $sourceData['Summative/Formative'] ?? '';
$yearLevel = $sourceData['Year'] ?? '';
$tutorComments = $sourceData['Comments'] ?? '';

$sql = "INSERT INTO questions (
    workspace_id,
    source_type,
    source_question_id,
    title,
    stem,
    lead_in,
    option_a,
    option_b,
    option_c,
    option_d,
    option_e,
    correct_answer,
    correct_answer_letter,
    justification,
    specialty,
    summative_formative,
    condition_name,
    presentation,
    skill,
    year_level,
    tutor_comments,
    tags,
    status
) VALUES (
    :workspace_id,
    :source_type,
    :source_question_id,
    :title,
    :stem,
    :lead_in,
    :option_a,
    :option_b,
    :option_c,
    :option_d,
    :option_e,
    :correct_answer,
    :correct_answer_letter,
    :justification,
    :specialty,
    :summative_formative,
    :condition_name,
    :presentation,
    :skill,
    :year_level,
    :tutor_comments,
    :tags,
    :status
)";

$stmt = $pdo->prepare($sql);
$stmt->execute([
    'workspace_id' => $job['workspace_id'],
    'source_type' => 'variant',
    'source_question_id' => $sourceRowNumber,
    'title' => $title,
    'stem' => $stem,
    'lead_in' => $lead_in,
    'option_a' => $option_a,
    'option_b' => $option_b,
    'option_c' => $option_c,
    'option_d' => $option_d,
    'option_e' => $option_e,
    'correct_answer' => $correct_answer,
    'correct_answer_letter' => $correct_answer_letter,
    'justification' => $justification,
    'specialty' => $specialty,
    'summative_formative' => $summativeFormative,
    'condition_name' => $conditionName,
    'presentation' => $presentation,
    'skill' => $skill,
    'year_level' => $yearLevel,
    'tutor_comments' => $tutorComments,
    'tags' => 'variant,sba',
    'status' => 'Draft'
]);

$question_id = $pdo->lastInsertId();

$newCompleted = ((int) $job['questions_completed']) + 1;
$newStatus = ($newCompleted >= (int) $job['num_questions']) ? 'complete' : 'running';

$sql = "UPDATE generation_jobs
        SET questions_completed = :questions_completed, status = :status
        WHERE id = :job_id";
$stmt = $pdo->prepare($sql);
$stmt->execute([
    'questions_completed' => $newCompleted,
    'status' => $newStatus,
    'job_id' => $job_id
]);

echo json_encode([
    'status' => 'success',
    'message' => 'One variant generated.',
    'job_id' => $job_id,
    'questions_completed' => $newCompleted,
    'num_questions' => (int) $job['num_questions'],
    'job_status' => $newStatus,
    'question' => [
        'id' => $question_id,
        'title' => $title,
        'stem' => $stem,
        'lead_in' => $lead_in,
        'option_a' => $option_a,
        'option_b' => $option_b,
        'option_c' => $option_c,
        'option_d' => $option_d,
        'option_e' => $option_e,
        'correct_answer_letter' => $correct_answer_letter,
        'correct_answer' => $correct_answer,
        'justification' => $justification,
        'specialty' => $specialty,
        'condition_name' => $conditionName,
        'presentation' => $presentation,
        'skill' => $skill,
        'summative_formative' => $summativeFormative,
        'year_level' => $yearLevel,
        'tutor_comments' => $tutorComments,
        'status' => 'Draft',
        'source_type' => 'variant',
        'source_question_id' => $sourceRowNumber,
        'variant_number' => $variantNumber
    ]
]);