'use strict'; const { createQuiz, saveQuiz, httpError, QUIZ_QUESTIONS_MAX, QUIZ_OPTIONS_MAX, QUIZ_TITLE_MAX, QUIZ_DESCRIPTION_MAX, QUIZ_TEXT_MAX, QUIZ_DESC_MAX, QUIZ_ANSWER_MAX, QUIZ_ACCEPTED_MAX, QUIZ_ACCEPTED_LEN, } = require('./quizzes'); const QUIZ_AI_PROMPT_MAX = 4000; const QUIZ_AI_QUESTIONS_DEFAULT = 10; const QUIZ_AI_QUESTIONS_MAX = 40; const QUIZ_AI_TIMEOUT_MS = 300000; const QUIZ_AI_DIFFICULTIES = new Set(['easy', 'medium', 'hard']); const QUIZ_AI_DIFFICULTY_LABELS = { easy: 'лёгкая', medium: 'средняя', hard: 'сложная' }; const QUIZ_AI_SYSTEM_PROMPT = [ 'Ты — методист образовательного центра и составляешь проверочные тесты и опросы по описанию пользователя.', 'Верни ТОЛЬКО валидный JSON без markdown-обёртки и без пояснений до или после него. Внутри полей description можно использовать Markdown.', 'Схема ответа:', '{"title":"string","description":"string","questions":[{"text":"string","kind":"single","description":"string","options":[{"text":"string","is_correct":true}],"accepted_answers":["string"]}]}', 'Правила:', '- kind — один из: single (один верный вариант), multiple (несколько верных), select (выпадающий список), line (короткий свободный ответ), text (развёрнутый свободный ответ), number (число), date (дата).', '- Для single, multiple и select обязательно от 2 до 25 вариантов в options; у single и select ровно один вариант с is_correct = true; у multiple минимум один.', '- Для line, text, number и date options не нужны; в тесте можно указать accepted_answers — список допустимых ответов для автопроверки.', '- Всегда заполняй description теста в Markdown: 1–3 коротких абзаца или список — что проверяет тест и как его проходить. Допустимы **жирный**, *курсив*, списки, `код`, таблицы и ссылки; без заголовков первого уровня, картинок и HTML.', '- Пояснения к вопросам (description) добавляй, только если пользователь прямо об этом просит, и оформляй их тоже в Markdown — кратко, 1–2 предложения или список.', '- Не добавляй description в вариантах ответа, если пользователь прямо об этом не просил.', '- Формулируй вопросы и варианты кратко — до 120 символов, без вступлений и пояснений.', '- Все тексты на русском языке; в текстах вопросов и вариантов — без нумерации вида «1.», без LaTeX и без служебных пометок.', '- Не выдумывай факты, которых нет в описании; раскрывай тему по существу и формулируй вопросы однозначно.', ].join('\n'); const KIND_ALIASES = { single: 'single', single_choice: 'single', singlechoice: 'single', radio: 'single', one: 'single', one_answer: 'single', multiple: 'multiple', multiple_choice: 'multiple', multiplechoice: 'multiple', checkbox: 'multiple', checkboxes: 'multiple', multi: 'multiple', select: 'select', dropdown: 'select', line: 'line', input: 'line', short: 'line', short_text: 'line', short_answer: 'line', text: 'text', long: 'text', long_text: 'text', textarea: 'text', free: 'text', number: 'number', numeric: 'number', int: 'number', integer: 'number', date: 'date', }; const FREE_KINDS = new Set(['line', 'text', 'number', 'date']); function strOf(value, max) { if (value == null) return ''; const text = String(value).replace(/\s+/g, ' ').trim(); return text.length > max ? text.slice(0, max) : text; } function blockOf(value, max) { if (value == null) return ''; const text = String(value).replace(/\r\n/g, '\n').trim(); return text.length > max ? text.slice(0, max) : text; } function stripNumbering(text) { return String(text || '').replace(/^\s*\d+[.)]\s+/, ''); } function normKind(value) { const key = String(value || '').trim().toLowerCase().replace(/[\s-]+/g, '_'); return KIND_ALIASES[key] || 'single'; } function clampCount(value) { const n = parseInt(value, 10); if (!Number.isFinite(n)) return QUIZ_AI_QUESTIONS_DEFAULT; return Math.max(1, Math.min(QUIZ_AI_QUESTIONS_MAX, n)); } function quizAiMaxTokens(count) { return Math.min(4096, Math.max(1024, count * 320 + 512)); } function quizAiUserPrompt({ prompt, kind, count, difficulty }) { const lines = [ `Тема и требования пользователя: ${prompt}`, `Формат: ${kind === 'survey' ? 'опрос без правильных ответов' : 'тест с правильными ответами'}.`, `Количество вопросов: ${count}.`, `Сложность: ${QUIZ_AI_DIFFICULTY_LABELS[difficulty] || QUIZ_AI_DIFFICULTY_LABELS.medium}.`, ]; if (kind === 'survey') lines.push('В вопросах с вариантами не указывай is_correct — просто перечисли варианты.'); else lines.push('Отметь правильные ответы is_correct = true и укажи accepted_answers там, где ответ вводится текстом.'); lines.push('Ответ — только JSON по схеме, без пояснений.'); return lines.join('\n'); } function stringField(text, key) { const re = new RegExp(`"${key}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`); const m = re.exec(text); if (!m) return ''; try { return JSON.parse('"' + m[1] + '"'); } catch (e) { return m[1]; } } function salvageQuestions(text) { const qKey = text.indexOf('"questions"'); const arrStart = qKey === -1 ? text.indexOf('[') : text.indexOf('[', qKey); if (arrStart === -1) return null; const objects = []; let depth = 0; let objStart = -1; let inString = false; let escaped = false; for (let i = arrStart + 1; i < text.length; i++) { const ch = text[i]; if (inString) { if (escaped) escaped = false; else if (ch === '\\') escaped = true; else if (ch === '"') inString = false; continue; } if (ch === '"') { inString = true; continue; } if (ch === '{') { if (depth === 0) objStart = i; depth++; } else if (ch === '}') { depth--; if (depth === 0 && objStart !== -1) { try { objects.push(JSON.parse(text.slice(objStart, i + 1))); } catch (e) { void e; } objStart = -1; } } else if (ch === ']' && depth === 0) { break; } } if (!objects.length) return null; return { title: stringField(text, 'title'), description: stringField(text, 'description'), questions: objects, }; } function extractJson(raw) { let text = String(raw || '').trim(); text = text.replace(/^```[a-z]*\s*/i, '').replace(/\s*```$/i, '').trim(); if (!text) throw httpError(502, 'Модель вернула пустой ответ'); const objStart = text.indexOf('{'); const arrStart = text.indexOf('['); const start = arrStart !== -1 && (objStart === -1 || arrStart < objStart) ? arrStart : objStart; if (start === -1) throw httpError(502, 'Модель вернула ответ без JSON'); const close = text[start] === '{' ? '}' : ']'; const end = text.lastIndexOf(close); if (end > start) { try { return JSON.parse(text.slice(start, end + 1)); } catch (e) { void e; } } const salvaged = salvageQuestions(text); if (salvaged) return salvaged; throw httpError(502, 'Модель вернула повреждённый JSON'); } function normOptions(raw) { const list = raw.options ?? raw.answers ?? raw.variants ?? raw.choices ?? raw.items; if (!Array.isArray(list)) return []; const seen = new Set(); const options = []; for (const item of list) { const source = typeof item === 'string' ? { text: item } : item; if (!source || typeof source !== 'object') continue; const text = stripNumbering(strOf(source.text ?? source.title ?? source.value ?? source.label, QUIZ_TEXT_MAX)); if (!text) continue; const key = text.toLowerCase(); if (seen.has(key)) continue; seen.add(key); options.push({ text, is_correct: source.is_correct === true || source.is_correct === 'true' || source.correct === true || source.correct === 'true', weight: 1 }); if (options.length >= QUIZ_OPTIONS_MAX) break; } return options; } function normAccepted(raw) { const list = raw.accepted_answers ?? raw.acceptedAnswers ?? raw.correct_answers ?? raw.answers; if (!Array.isArray(list)) return []; const seen = new Set(); const accepted = []; for (const item of list) { const text = strOf(typeof item === 'object' && item ? item.text : item, QUIZ_ACCEPTED_LEN); if (!text) continue; const key = text.toLowerCase(); if (seen.has(key)) continue; seen.add(key); accepted.push(text); if (accepted.length >= QUIZ_ACCEPTED_MAX) break; } return accepted; } function normQuestion(raw, quizKind) { if (!raw || typeof raw !== 'object') return null; const text = stripNumbering(blockOf(raw.text ?? raw.question ?? raw.title ?? raw.prompt, QUIZ_TEXT_MAX)); if (!text) return null; const kind = normKind(raw.kind ?? raw.type ?? raw.question_type); const free = FREE_KINDS.has(kind); const question = { kind, text, description: blockOf(raw.description ?? raw.note, QUIZ_DESC_MAX) || null, weight: 1, partial_credit: false, required: true, min_length: 0, options_inline: false, text_match: 'exact', accepted_answers: [], asset_ids: [], options: [], }; if (free) { if (quizKind === 'test') question.accepted_answers = normAccepted(raw); return question; } const options = normOptions(raw); if (options.length < 2) return null; if (quizKind === 'test') { const correct = options.filter(o => o.is_correct); if (kind === 'multiple') { if (!correct.length) options[0].is_correct = true; } else { const keep = correct[0] || options[0]; options.forEach(o => { o.is_correct = o === keep; }); } } else { options.forEach(o => { o.is_correct = false; }); } question.options = options; return question; } function normalizeDraft(raw, { kind, count, fallbackTitle }) { let body = raw; if (Array.isArray(body)) body = { questions: body }; if (body && typeof body === 'object' && !Array.isArray(body.questions)) { const nested = body.quiz || body.test || body.survey || body.data; if (nested && typeof nested === 'object' && !Array.isArray(nested)) body = nested; } if (!body || typeof body !== 'object') throw httpError(502, 'Модель вернула неожиданный формат ответа'); const list = Array.isArray(body.questions) ? body.questions : Array.isArray(body.items) ? body.items : Array.isArray(body.quiz) ? body.quiz : []; const limit = Math.min(count, QUIZ_QUESTIONS_MAX); const questions = []; for (const item of list) { const question = normQuestion(item, kind); if (!question) continue; questions.push(question); if (questions.length >= limit) break; } if (!questions.length) throw httpError(502, 'Модель не вернула ни одного корректного вопроса'); return { title: strOf(body.title ?? body.name, QUIZ_TITLE_MAX) || fallbackTitle, description: blockOf(body.description ?? body.summary, QUIZ_DESCRIPTION_MAX), questions, }; } function normalizeQuizAiRequest(body = {}) { const prompt = String(body.prompt ?? '').trim(); if (!prompt) throw httpError(400, 'Опишите тему теста'); if (prompt.length > QUIZ_AI_PROMPT_MAX) { throw httpError(400, `Описание не может быть длиннее ${QUIZ_AI_PROMPT_MAX} символов`); } const kind = body.kind === 'survey' ? 'survey' : 'test'; const count = clampCount(body.count); const difficulty = QUIZ_AI_DIFFICULTIES.has(String(body.difficulty)) ? String(body.difficulty) : 'medium'; const rawProfile = body.profile ?? body.model; const profile = rawProfile == null ? '' : String(rawProfile); return { prompt, kind, count, difficulty, profile }; } async function generateQuizDraft(pool, user, body, deps) { const request = normalizeQuizAiRequest(body); const { prompt, kind, count, difficulty, profile: profileId } = request; const profile = await deps.resolveProfile(profileId, user.id); if (profileId && profileId !== 'native' && !profile) throw httpError(400, 'Профиль ИИ не найден'); let answer; try { answer = await deps.complete( QUIZ_AI_SYSTEM_PROMPT, quizAiUserPrompt({ prompt, kind, count, difficulty }), quizAiMaxTokens(count), profile, QUIZ_AI_TIMEOUT_MS ); } catch (e) { if (e && e.name === 'AbortError') { throw httpError(504, `Модель не ответила за ${Math.round(QUIZ_AI_TIMEOUT_MS / 1000)} с — попробуйте меньше вопросов или другую модель`); } throw httpError(502, 'Сервис ИИ недоступен: ' + (e && e.message ? e.message : 'ошибка запроса')); } const fallbackTitle = kind === 'survey' ? `Опрос: ${prompt.slice(0, 120)}` : `Тест: ${prompt.slice(0, 120)}`; const draft = normalizeDraft(extractJson(answer), { kind, count, fallbackTitle }); const created = await createQuiz(pool, user, { kind, title: draft.title }); const id = created.quiz.id; let saved; try { saved = await saveQuiz(pool, id, user, { kind, title: draft.title, description: draft.description || null, is_published: false, show_results: true, questions: draft.questions, }); } catch (e) { await pool.query('DELETE FROM quizzes WHERE id = $1', [id]).catch(() => {}); if (e && e.status) throw httpError(502, 'Модель вернула вопросы, которые не прошли проверку: ' + e.message); throw e; } return { quiz: { id, title: saved.quiz.title, kind: saved.quiz.kind }, questions: draft.questions.length, model: profile ? profile.model : 'native', }; } module.exports = { QUIZ_AI_PROMPT_MAX, QUIZ_AI_QUESTIONS_DEFAULT, QUIZ_AI_QUESTIONS_MAX, QUIZ_AI_TIMEOUT_MS, QUIZ_AI_SYSTEM_PROMPT, quizAiMaxTokens, quizAiUserPrompt, extractJson, normalizeDraft, normalizeQuizAiRequest, generateQuizDraft, };