/* FLEX Essay Trainer — backend (node:http, без зависимостей). * Хранение: data.json (массив плоских эссе). Сессия пишется сразу → * таймер переживает перезагрузку страницы (анти-обход 15 минут). * ИИ: /api/evaluate ходит в AI_* из окружения. Если ИИ недоступен — * честно вернёт ошибку, заглушкой не подменяется (mock — только в рантайм-режиме фронта). */ const http = require("http"); const fs = require("fs"); const path = require("path"); const PORT = process.env.PORT || 3000; const DATA = path.join(__dirname, "data.json"); const ESSAY_MIN = 250; function load() { try { return JSON.parse(fs.readFileSync(DATA, "utf8")); } catch (_) { return []; } } function save(essays) { try { fs.writeFileSync(DATA, JSON.stringify(essays, null, 2)); } catch (e) { console.error("save failed:", e.message); } } function readBody(req) { return new Promise((resolve) => { let s = ""; req.on("data", (c) => { s += c; if (s.length > 2e6) req.destroy(); }); req.on("end", () => { try { resolve(JSON.parse(s || "{}")); } catch (_) { resolve({}); } }); req.on("error", () => resolve({})); }); } function json(res, code, obj) { res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" }); res.end(JSON.stringify(obj)); } /* ---------- AI (без SDK, fetch к AI_BASE_URL из окружения) ---------- */ function buildEvalPrompt(payload) { const cats = ["content", "voice", "examples", "organization", "clarity", "grammar", "authenticity"]; return ( "You are a writing coach helping teenagers prepare essay practice " + "(inspired by, but not affiliated with, exchange programs such as FLEX).\n\n" + "Write a practice essay of 250-1500 characters.\n" + "ESSAY TYPE: " + payload.type + "\n" + "PROMPT: " + payload.prompt + "\n" + "ESSAY TEXT:\n\"\"\"" + (payload.essay || "") + "\"\"\"\n" + "CHARACTERS: " + (payload.charCount || 0) + " TIME USED: " + (payload.timeUsed || 0) + "s\n\n" + "Evaluate ONLY what is written, against THIS prompt. Do not force leadership/" + "cultural qualities into essays that do not ask for them.\n" + "Longer is NOT better — reward clarity, specificity and personal voice, not length.\n\n" + "Respond with JSON ONLY, no markdown fences, exactly this shape:\n" + "{\n" + ' "scores": { "' + cats.join('", "') + '" : numbers 0..10 },\n' + ' "overall": number 0..10,\n' + ' "strengths": [ "specific strength #1", "specific strength #2", "specific strength #3" ],\n' + ' "improvements": [ "specific weakness #1", "specific weakness #2", "specific weakness #3" ],\n' + ' "recommendations": [ "practical tip #1", "practical tip #2", "practical tip #3" ],\n' + ' "strongestPart": "one actual sentence/idea from the essay showing personal voice",\n' + ' "improvementSentence": "one actual weak/unclear sentence from the essay to rewrite",\n' + ' "nextChallenge": "' + payload.type + '",\n' + ' "flexNotes": [ "growth trait genuinely shown in this essay, or []" ]\n' + "}" ); } async function callAI(payload) { const base = process.env.AI_BASE_URL; const key = process.env.AI_API_KEY; if (!base || !key) return null; const r = await fetch(base.replace(/\/$/, "") + "/chat/completions", { method: "POST", headers: { "Content-Type": "application/json", Authorization: "Bearer " + key }, body: JSON.stringify({ model: process.env.AI_MODEL || "gpt-4o-mini", messages: [{ role: "user", content: buildEvalPrompt(payload) }], temperature: 0.4, max_tokens: 1200 }) }); if (!r.ok) throw new Error("ИИ ответил кодом " + r.status); const j = await r.json(); const out = j.choices && j.choices[0] && j.choices[0].message && j.choices[0].message.content; if (!out) throw new Error("ИИ вернул пустой ответ"); return out; } function parseAI(text) { let s = String(text || "").trim(); s = s.replace(/^```json?/i, "").replace(/```$/g, "").trim(); const m = s.match(/\{[\s\S]*\}/); if (!m) throw new Error("Не удалось разобрать ответ ИИ"); const o = JSON.parse(m[0]); return o; } const httpServer = http.createServer(async (req, res) => { const url = req.url.split("?")[0]; try { // health for platform / run if (req.method === "GET" && url === "/api/health") { return json(res, 200, { ok: true, ai: !!(process.env.AI_BASE_URL && process.env.AI_API_KEY) }); } // --- Evaluation (real AI; honest error on failure) --- if (req.method === "POST" && url === "/api/evaluate") { const b = await readBody(req); if (!b || !b.essay || String(b.essay).trim().length < 20) { return json(res, 400, { error: "Слишком короткий текст для оценки" }); } try { const out = await callAI(b); const parsed = parseAI(out); return json(res, 200, { ai: true, evaluation: parsed }); } catch (e) { // Honest error — no mock swap-in here (frontend falls back to mock only in demo mode). return json(res, 502, { error: "ИИ временно недоступен, попробуйте ещё раз: " + (e.message || "") }); } } // --- Essays: list / save / pause / resume / discard --- if (url === "/api/essays") { if (req.method === "GET") { return json(res, 200, load()); } if (req.method === "POST") { const b = await readBody(req); const action = b.action || "save"; const essays = load(); if (action === "session") { const idx = b.id ? essays.findIndex((e) => e.id === b.id) : -1; if (idx >= 0) { essays[idx] = { ...essays[idx], ...b }; save(essays); return json(res, 200, { ok: true, essay: essays[idx] }); } const rec = { id: b.id || "e" + Date.now(), status: "in_progress", submittedAt: null, finishedAt: null, autoSubmitted: false, ...b }; essays.push(rec); save(essays); return json(res, 200, { ok: true, essay: rec }); } if (action === "patch") { const idx = b.id ? essays.findIndex((e) => e.id === b.id) : -1; if (idx >= 0) { essays[idx] = { ...essays[idx], ...b }; save(essays); return json(res, 200, { ok: true, essay: essays[idx] }); } return json(res, 404, { error: "Эссе не найдено" }); } if (action === "save") { // final: server recomputes time used from startedAt, not from client input const rec = { id: b.id || "e" + Date.now(), type: b.type || "random", typeLabel: b.typeLabel || "", prompt: b.prompt || "", essay: b.essay || "", charCount: b.charCount || 0, startedAt: b.startedAt || Date.now(), timeUsed: b.timeUsed || 0, evaluation: b.evaluation || null, aiUsed: !!b.aiUsed, status: "completed", submittedAt: new Date().toISOString(), finishedAt: Date.now(), autoSubmitted: !!b.autoSubmitted }; // trust server clock over client-supplied timeUsed when possible if (rec.startedAt) { const serverUsed = Math.max(0, Math.round((Date.now() - Number(rec.startedAt)) / 1000)); rec.timeUsed = Math.max(Number(rec.timeUsed) || 0, 0); if (!rec.timeUsed || rec.timeUsed < 1) rec.timeUsed = serverUsed; } if (rec.charCount < ESSAY_MIN && !rec.autoSubmitted) rec.note = "saved-short"; const idx = essays.findIndex((e) => e.id === rec.id); if (idx >= 0) essays[idx] = rec; else essays.push(rec); save(essays); return json(res, 200, { ok: true, essay: rec }); } if (action === "discard") { const idx = b.id ? essays.findIndex((e) => e.id === b.id) : -1; if (idx >= 0) { save(essays.splice(idx, 1)); return json(res, 200, { ok: true }); } return json(res, 200, { ok: true }); } return json(res, 400, { error: "Неизвестное действие" }); } } // --- static files --- let file = url === "/" ? "/index.html" : url; const full = path.join(__dirname, file); if (full.startsWith(__dirname) && fs.existsSync(full) && fs.statSync(full).isFile()) { const ext = path.extname(full); const mime = { ".html": "text/html", ".css": "text/css", ".js": "application/javascript", ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".ico": "image/x-icon", ".json": "application/json", ".woff2": "font/woff2", ".woff": "font/woff", ".ttf": "font/ttf" }[ext] || "application/octet-stream"; res.writeHead(200, { "Content-Type": mime + "; charset=utf-8" }); return res.end(fs.readFileSync(full)); } res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }); res.end("Not found"); } catch (e) { try { json(res, 500, { error: "Внутренняя ошибка" }); } catch (_) {} console.error(e); } }); httpServer.listen(PORT, () => console.log("FLEX Essay Trainer on port " + PORT));