import { NextRequest, NextResponse } from "next/server"; import { claude, parseClaudeJson } from "@/lib/claude"; import { prisma } from "@/lib/db"; // import { Prisma } from "@prisma/client"; import { calculateXpGain, rollCriticalHit } from "@/lib/xp"; import { checkLevelUp } from "@/lib/progression"; import { EXERCISE_XP } from "@/config/xp"; import { getArticleBySlug } from "@/lib/reading/articles"; import type { ComprehensionQuestion } from "@/app/api/reading/questions/route"; import { processSkillUnlocks } from "@/lib/skill-unlock"; import { getMultiplierPercent } from "@/lib/multiplier"; import { getTitleForLevel } from "@/config/titles"; import { withApiError } from "@/lib/api-error"; import { processEndOfDay } from "@/lib/streak"; interface ScoreBody { slug?: string; content?: { title: string; body: string; sourceUrl?: string }; answers: { questionId: number; answer: string }[]; questions: ComprehensionQuestion[]; durationSecs: number; userId?: number; } interface QuestionScore { questionId: number; score: number; // 0-10 feedback: string; } interface ClaudeScoreResponse { scores: QuestionScore[]; overallFeedback: string; } /** * POST /api/reading/score * * Scores comprehension answers via Claude, calculates XP, persists to DB. */ export const POST = withApiError(async (request: NextRequest) => { if (!process.env.ANTHROPIC_API_KEY) { return NextResponse.json( { error: "ANTHROPIC_API_KEY is not configured" }, { status: 503 }, ); } let body: ScoreBody; try { body = await request.json(); } catch { return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); } const { slug, content, answers, questions, durationSecs } = body; if (!answers || !questions || answers.length === 0) { return NextResponse.json( { error: "answers and questions are required" }, { status: 400 }, ); } // Resolve article content — seeded slug or custom content let articleTitle: string; let isCustomContent = false; let sourceUrl = ""; if (slug && typeof slug === "string") { const article = getArticleBySlug(slug); if (!article) { return NextResponse.json({ error: "Article not found" }, { status: 404 }); } articleTitle = article.title; } else if ( content && typeof content.title === "string" && typeof content.body === "string" ) { articleTitle = content.title; isCustomContent = true; sourceUrl = content.sourceUrl ?? ""; } else { return NextResponse.json( { error: "Provide either a 'slug' or 'content' object" }, { status: 400 }, ); } // Build Q&A pairs for Claude const qaPairs = questions.map((q) => { const a = answers.find((ans) => ans.questionId === q.id); return { question: q.question, type: q.type, answer: a?.answer ?? "" }; }); let scored: ClaudeScoreResponse; try { const message = await claude.messages.create({ model: "claude-haiku-4-5-20251001", max_tokens: 2048, messages: [ { role: "user", content: `You are scoring comprehension answers for a reading exercise. The reader answered from memory after reading the article — they no longer had access to the text. Score each answer 0-10 based on accuracy, depth, and relevance to the question. Be fair but rigorous — a vague or partially correct answer should score 4-6, not 8-10. Respond ONLY in valid JSON (no markdown, no code fences): { "scores": [ { "questionId": 1, "score": N, "feedback": "..." }, ... ], "overallFeedback": "..." } Article: "${articleTitle}" Questions and answers: ${qaPairs.map((qa, i) => `Q${i + 1} [${qa.type}]: ${qa.question}\nAnswer: ${qa.answer}`).join("\n\n")}`, }, ], }); const text = message.content[0].type === "text" ? message.content[0].text : "{}"; scored = parseClaudeJson(text) as ClaudeScoreResponse; } catch (err) { return NextResponse.json( { error: "Failed to score answers", details: err instanceof Error ? err.message : String(err), }, { status: 500 }, ); } // Quality score: average of all question scores / 10 const avgScore = scored.scores.reduce((sum, s) => sum + s.score, 0) / scored.scores.length; const qualityScore = avgScore / 10; // --- Fetch user --- const userId = body.userId ?? 1; const user = await prisma.user.findFirst({ where: { id: userId }, include: { categorySkills: { where: { category: "reading" } } }, }); if (!user) { return NextResponse.json({ error: "No user found" }, { status: 404 }); } const readingSkill = user.categorySkills[0]; if (!readingSkill) { return NextResponse.json( { error: "Reading CategorySkill not found" }, { status: 500 }, ); } // --- XP calculation (with skill tree multiplier) --- const { baseXp, maxQualityBonus } = EXERCISE_XP["reading"]; const isCriticalHit = rollCriticalHit(); const multiplierPercent = await getMultiplierPercent(prisma, userId, "reading"); const xpResult = calculateXpGain({ baseXp, qualityScore, maxQualityBonus, isCriticalHit, multiplierPercent, }); // Level-up checks const userLevelResult = checkLevelUp({ currentXp: user.currentXp + xpResult.totalXp, xpToNextLevel: user.xpToNextLevel, level: user.level, }); const categoryLevelResult = checkLevelUp({ currentXp: readingSkill.currentXp + xpResult.totalXp, xpToNextLevel: readingSkill.xpToNext, level: readingSkill.level, }); // --- Title progression --- const newTitle = getTitleForLevel(userLevelResult.newLevel); const titleChanged = newTitle !== user.title; // --- Streak processing (idempotent — no-op if already run today) --- await processEndOfDay(userId); // Daily log bookkeeping const now = new Date(); const todayStart = new Date( Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()), ); const tomorrowStart = new Date(todayStart.getTime() + 86_400_000); const existingLog = await prisma.dailyLog.findFirst({ where: { userId, date: { gte: todayStart, lt: tomorrowStart } }, }); const newXpEarned = (existingLog?.xpEarned ?? 0) + xpResult.totalXp; const newActivityCount = (existingLog?.activityCount ?? 0) + 1; const goalMet = newXpEarned >= user.dailyGoalXp; let unlockResult = { unlocked: [] as string[], streakFreezesGranted: 0 }; await prisma.$transaction(async (tx) => { await tx.activity.create({ data: { userId, category: "reading", exerciseType: isCustomContent ? "comprehension-custom" : "comprehension", description: `Read & comprehended: ${articleTitle}`, baseXp: xpResult.baseXp, qualityBonus: xpResult.qualityBonus, isCriticalHit: xpResult.isCriticalHit, totalXp: xpResult.totalXp, score: qualityScore, durationSecs, metadata: JSON.stringify({ ...(slug ? { slug } : {}), articleTitle, avgScore, questionCount: questions.length, ...(isCustomContent && { custom: true }), ...(sourceUrl && { sourceUrl }), }), }, }); await tx.user.update({ where: { id: userId }, data: { totalXp: user.totalXp + xpResult.totalXp, currentXp: userLevelResult.remainingXp, xpToNextLevel: userLevelResult.newXpToNextLevel, level: userLevelResult.newLevel, ...(titleChanged && { title: newTitle }), }, }); await tx.categorySkill.update({ where: { id: readingSkill.id }, data: { totalXp: readingSkill.totalXp + xpResult.totalXp, currentXp: categoryLevelResult.remainingXp, xpToNext: categoryLevelResult.newXpToNextLevel, level: categoryLevelResult.newLevel, }, }); // Auto-unlock skill tree nodes if category leveled up if (categoryLevelResult.levelsGained > 0) { unlockResult = await processSkillUnlocks( tx, userId, "reading", categoryLevelResult.newLevel, ); } if (existingLog) { await tx.dailyLog.update({ where: { id: existingLog.id }, data: { xpEarned: newXpEarned, activityCount: newActivityCount, goalMet }, }); } else { await tx.dailyLog.create({ data: { userId, date: todayStart, xpEarned: newXpEarned, activityCount: newActivityCount, goalMet, }, }); } }); return NextResponse.json({ scores: scored.scores, overallFeedback: scored.overallFeedback, avgScore, xp: { baseXp: xpResult.baseXp, totalXp: xpResult.totalXp, qualityBonus: xpResult.qualityBonus, multiplierBonus: xpResult.multiplierBonus, multiplierPercent, isCriticalHit: xpResult.isCriticalHit, }, levelUp: userLevelResult.levelsGained > 0, categoryXp: { currentXp: categoryLevelResult.remainingXp, xpToNext: categoryLevelResult.newXpToNextLevel, level: categoryLevelResult.newLevel, levelUp: categoryLevelResult.levelsGained > 0, }, newTitle: titleChanged ? newTitle : undefined, unlocks: unlockResult.unlocked, streakFreezesGranted: unlockResult.streakFreezesGranted, }); });