<?php

/**
 * Form-based question generator: link questions to a generation_jobs row via tags (no schema change),
 * and fetch prior questions in the same batch for anti-repetition context in the LLM prompt.
 */

/**
 * Tag fragment stored on each question row for this batch (comma-delimited tags column).
 */
function generatorFormBatchJobTag(int $generationJobId): string
{
    return 'batch_job_id=' . $generationJobId;
}

function generatorParseBatchJobIdFromTags(string $tags): int
{
    if (preg_match('/\bbatch_job_id=(\d+)\b/', $tags, $m)) {
        return max(0, (int) $m[1]);
    }

    return 0;
}

/**
 * @return list<array<string, mixed>>
 */
function fetchFormGeneratorPriorQuestionsInBatch(PDO $pdo, string $workspaceId, int $generationJobId): array
{
    if ($generationJobId < 1 || $workspaceId === '') {
        return [];
    }

    $needle = ',' . generatorFormBatchJobTag($generationJobId) . ',';
    $sql = 'SELECT title, stem, lead_in, option_a, option_b, option_c, option_d, option_e, '
        . 'correct_answer, correct_answer_letter, tags, skill, justification '
        . 'FROM questions '
        . 'WHERE workspace_id = :workspace_id '
        . 'AND source_type = :source_type '
        . 'AND CONCAT(\',\', IFNULL(tags, \'\'), \',\') LIKE :tag_like '
        . 'ORDER BY id ASC';

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        'workspace_id' => $workspaceId,
        'source_type' => 'generated',
        'tag_like' => '%' . $needle . '%',
    ]);

    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    return is_array($rows) ? $rows : [];
}
