<?php

ini_set('display_errors', '0');
error_reporting(E_ALL);
ob_start();

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

set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
    error_log('[start_generation_job] PHP warning: ' . $message . ' in ' . $file . ':' . $line);

    return true;
});

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../ai/form_generator_default_skills.php';
require_once __DIR__ . '/../../prompts/generator_prompt.php';

/**
 * @param array<string, mixed> $payload
 */
function startGenerationJsonResponse(array $payload): void
{
    while (ob_get_level() > 0) {
        ob_end_clean();
    }
    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
}

function startGenerationFail(string $detail): void
{
    startGenerationJsonResponse([
        'ok' => false,
        'status' => 'error',
        'error' => 'Generation could not be started',
        'detail' => $detail,
        'message' => 'Generation could not be started. No draft was saved.',
    ]);
}

try {
    $workspace_id = $_POST['workspace_id'] ?? '';
    $specialty = trim((string) ($_POST['specialty'] ?? ''));
    $core_condition = trim((string) ($_POST['core_condition'] ?? ''));
    $presentation = trim((string) ($_POST['presentation'] ?? ''));
    $learning_outcome = $_POST['learning_outcome'] ?? '';
    $skills = $_POST['skills'] ?? [];
    $summative_formative = $_POST['summative_formative'] ?? '';
    $year_level = $_POST['year'] ?? '';
    $tutor_comments = trim((string) ($_POST['tutor_comments'] ?? ''));

    if (empty($workspace_id)) {
        startGenerationFail('Missing workspace ID.');
    }

    if ($specialty === '') {
        startGenerationFail('Specialty is required.');
    }

    if ($core_condition === '') {
        startGenerationFail('Core condition is required.');
    }

    if ($presentation === '') {
        startGenerationFail('Presentation is required.');
    }

    if (empty($summative_formative)) {
        startGenerationFail('Missing summative/formative value.');
    }

    if (empty($year_level)) {
        startGenerationFail('Year level is required.');
    }

    $year_level = trim((string) $year_level);
    $allowed_year_levels = function_exists('aktYearLevelAllowedFormValues')
        ? aktYearLevelAllowedFormValues()
        : ['4', '5', '6'];
    if (!in_array($year_level, $allowed_year_levels, true)) {
        startGenerationFail('Invalid year level. Select Year 4, Year 5, or Year 6.');
    }

    $skills_input = is_array($skills) ? $skills : [];
    $skills_list = formGeneratorNormalizeManualSkillsList($skills_input);
    if ($skills_list === []) {
        startGenerationFail('Select at least one skill to generate questions.');
    }

    $num_questions = count($skills_list);
    $skills_string = formGeneratorSkillsListToJobCsv($skills_list);

    $sql = "INSERT INTO generation_jobs (
    workspace_id,
    specialty,
    condition_name,
    presentation,
    learning_outcome,
    num_questions,
    questions_completed,
    status,
    skills,
    summative_formative,
    year_level,
    tutor_comments
) VALUES (
    :workspace_id,
    :specialty,
    :condition_name,
    :presentation,
    :learning_outcome,
    :num_questions,
    0,
    'running',
    :skills,
    :summative_formative,
    :year_level,
    :tutor_comments
)";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
    'workspace_id' => $workspace_id,
    'specialty' => $specialty,
    'condition_name' => $core_condition,
    'presentation' => $presentation,
    'learning_outcome' => $learning_outcome,
    'num_questions' => $num_questions,
    'skills' => $skills_string,
    'summative_formative' => $summative_formative,
    'year_level' => $year_level,
    'tutor_comments' => $tutor_comments
    ]);

    $job_id = $pdo->lastInsertId();

    startGenerationJsonResponse([
        'ok' => true,
        'status' => 'success',
        'message' => 'Generation job created.',
        'job_id' => $job_id,
        'skills' => $skills_string,
        'num_questions' => $num_questions,
        'skills_inferred' => false,
    ]);
} catch (Throwable $e) {
    error_log('[start_generation_job] Exception: ' . $e->getMessage());
    startGenerationFail('Unexpected server error while starting generation.');
} finally {
    restore_error_handler();
}
