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 { processSkillUnlocks } from "@/lib/skill-unlock"; import { getMultiplierPercent } from "@/lib/multiplier"; import { getTitleForLevel } from "@/config/titles"; import { withApiError } from "@/lib/api-error"; import { addToReviewQueue, recordReview, REVIEW_XP_MULTIPLIER } from "@/lib/spaced-repetition"; import { processEndOfDay } from "@/lib/streak"; interface ScoreBody { topic: string; topicId?: string; explanation: string; userId?: number; wasTaught?: boolean; deepDiveRequested?: boolean; isReview?: boolean; // true when this is a spaced repetition review domain?: string; difficulty?: string; durationSecs?: number; } interface ClaudeScoreResponse { accuracy: number; completeness: number; clarity: number; gaps: string[]; feedback: string; } 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 { topic, topicId, explanation, wasTaught, deepDiveRequested, isReview, domain, difficulty, durationSecs } = body; if (!topic || typeof topic !== "string") { return NextResponse.json({ error: "topic is required" }, { status: 400 }); } if (!explanation || typeof explanation !== "string") { return NextResponse.json( { error: "explanation is required" }, { status: 400 }, ); } // --- Call Claude to evaluate the explanation --- const taughtContext = wasTaught ? `\n\nIMPORTANT CONTEXT: The user was first taught about this topic before explaining it. They did NOT know this topic beforehand. Adjust your evaluation accordingly: - Accuracy: Are the core facts correct? (Be slightly more lenient — they just learned this) - Completeness: Did they grasp the main idea and key takeaways? (Don't expect depth beyond what was taught) - Clarity: Can they explain it in their OWN words, not just parrot back what they read? (This is the most important dimension — penalize if it reads like a copy of teaching material) Focus on whether they truly understood and internalized the concept vs. just memorizing phrases.` : ""; let scores: ClaudeScoreResponse; try { const message = await claude.messages.create({ model: "claude-haiku-4-5-20251001", max_tokens: 1024, messages: [ { role: "user", content: `You are evaluating a Feynman-technique explanation. The user was asked to explain "${topic}"${wasTaught ? " after being taught about it" : " from memory, without reference materials"}. Score on three dimensions (0-10 each): - Accuracy: Are the facts correct? - Completeness: Are the key concepts covered? - Clarity: Would a beginner understand this? ${taughtContext} Respond ONLY in valid JSON (no markdown, no code fences): { "accuracy": N, "completeness": N, "clarity": N, "gaps": ["..."], "feedback": "..." } Here is the user's explanation: ${explanation}`, }, ], }); const text = message.content[0].type === "text" ? message.content[0].text : ""; scores = parseClaudeJson(text) as ClaudeScoreResponse; } catch (err) { return NextResponse.json( { error: "Failed to evaluate explanation", details: err instanceof Error ? err.message : String(err), }, { status: 500 }, ); } // --- Fetch user --- const userId = body.userId ?? 1; const user = await prisma.user.findFirst({ where: { id: userId }, include: { categorySkills: { where: { category: "feynman" } } }, }); if (!user) { return NextResponse.json({ error: "No user found" }, { status: 404 }); } const feynmanSkill = user.categorySkills[0]; if (!feynmanSkill) { return NextResponse.json( { error: "Feynman CategorySkill not found" }, { status: 500 }, ); } // --- XP calculation (with skill tree multiplier) --- // Taught topics earn 75% XP — still rewarding (you learned something new!) // Reviews earn 50% XP — reinforcement, not new learning // Normal explanations earn full XP const TAUGHT_XP_MULTIPLIER = 0.75; const qualityScore = (scores.accuracy + scores.completeness + scores.clarity) / 30; const rawXp = EXERCISE_XP["feynman"]; const xpMultiplier = isReview ? REVIEW_XP_MULTIPLIER : wasTaught ? TAUGHT_XP_MULTIPLIER : 1; const baseXp = Math.round(rawXp.baseXp * xpMultiplier); const maxQualityBonus = Math.round(rawXp.maxQualityBonus * xpMultiplier); const isCriticalHit = rollCriticalHit(); const multiplierPercent = await getMultiplierPercent(prisma, userId, "feynman"); 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: feynmanSkill.currentXp + xpResult.totalXp, xpToNextLevel: feynmanSkill.xpToNext, level: feynmanSkill.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; // --- Persist all changes in a transaction --- let unlockResult = { unlocked: [] as string[], streakFreezesGranted: 0 }; await prisma.$transaction(async (tx) => { await tx.activity.create({ data: { userId, category: "feynman", exerciseType: wasTaught ? "learn-and-explain" : "explain", description: wasTaught ? `Learned & explained: ${topic}` : `Feynman explanation: ${topic}`, baseXp: xpResult.baseXp, qualityBonus: xpResult.qualityBonus, isCriticalHit: xpResult.isCriticalHit, totalXp: xpResult.totalXp, score: qualityScore, durationSecs: typeof durationSecs === "number" && durationSecs >= 0 ? Math.round(durationSecs) : null, metadata: JSON.stringify({ topic, wasTaught: !!wasTaught, deepDiveRequested: !!deepDiveRequested, accuracy: scores.accuracy, completeness: scores.completeness, clarity: scores.clarity, }), }, }); 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: feynmanSkill.id }, data: { totalXp: feynmanSkill.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, "feynman", 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, }, }); } }); // --- Spaced repetition --- // If this was a taught topic, add it to the review queue // If this was a review, record the result and advance/reset stage let reviewResult: { advanced?: boolean; reset?: boolean; completed?: boolean; previousStage?: number; newStage?: number; } | null = null; if (isReview && topicId) { try { const result = await recordReview(userId, topicId, qualityScore); reviewResult = { advanced: result.advanced, reset: result.reset, completed: result.completed, previousStage: result.previousStage, newStage: result.newStage, }; } catch { // Non-fatal: review recording failure shouldn't block XP } } else if (wasTaught && topicId) { try { await addToReviewQueue({ userId, topicId, topic, domain: domain ?? "Unknown", difficulty: difficulty ?? "beginner", }); } catch { // Non-fatal: queue insertion failure shouldn't block XP } } return NextResponse.json({ scores: { accuracy: scores.accuracy, completeness: scores.completeness, clarity: scores.clarity, }, gaps: scores.gaps, feedback: scores.feedback, wasTaught: !!wasTaught, isReview: !!isReview, review: reviewResult, 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, }); });