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 { FLAW_FINDER_PASSAGES, STEELMAN_POSITIONS, DEVILS_ADVOCATE_POSITIONS, type ExerciseType, } from "@/lib/critical/passages"; import { runDebateScoring, type DebateScoreResult } from "@/lib/critical/debate-scorer"; 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 FlawFinderBody { exerciseType: "flaw-finder"; passageId: string; response: string; // user's written identification of flaws userId?: number; durationSecs?: number; } interface SteelmanBody { exerciseType: "steelman"; positionId: string; response: string; userId?: number; durationSecs?: number; } interface DevilsAdvocateBody { exerciseType: "devils-advocate"; positionId: string; response: string; userId?: number; durationSecs?: number; } type ScoreBody = FlawFinderBody | SteelmanBody | DevilsAdvocateBody; interface ClaudeScoreResult { scores: Record; // dimension → 0-10 overallScore: number; // 0-10 feedback: string; strengths: string[]; improvements: string[]; } // --------------------------------------------------------------------------- // Build Claude prompts per exercise type // --------------------------------------------------------------------------- function buildFlawFinderPrompt(passageId: string, response: string): string | null { const passage = FLAW_FINDER_PASSAGES.find((p) => p.id === passageId); if (!passage) return null; const answerKey = passage.fallacies .map((f, i) => `${i + 1}. ${f.name}: "${f.quote}" — ${f.explanation}`) .join("\n"); return `You are evaluating a critical thinking exercise. The user was given this passage and asked to identify logical fallacies: PASSAGE: "${passage.passage}" ANSWER KEY (do not share this with the user — use it to evaluate accuracy): ${answerKey} USER'S RESPONSE: ${response} Score the user on three dimensions (0–10 each): - Identification: Did they spot the right fallacies (or close equivalents)? - Accuracy: Did they explain the fallacy correctly? - Depth: Did they explain WHY the reasoning is flawed, not just name it? Respond ONLY in valid JSON (no markdown, no code fences): { "scores": { "identification": N, "accuracy": N, "depth": N }, "overallScore": N, "feedback": "...", "strengths": ["..."], "improvements": ["..."] }`; } function buildSteelmanPrompt(positionId: string, response: string): string | null { const position = STEELMAN_POSITIONS.find((p) => p.id === positionId); if (!position) return null; return `You are evaluating a steelman exercise. The user was asked to construct the strongest possible case FOR this position: POSITION: "${position.position}" DOMAIN: ${position.domain} The user should present the most charitable, rigorous version of this argument — not their personal opinion. USER'S RESPONSE: ${response} Score on three dimensions (0–10 each): - Charitable Interpretation: Does the response represent the position at its strongest? - Coherence: Is the argument logically structured and internally consistent? - Evidence & Reasoning: Does it cite relevant evidence, examples, or principled arguments? Respond ONLY in valid JSON (no markdown, no code fences): { "scores": { "charitableInterpretation": N, "coherence": N, "evidenceAndReasoning": N }, "overallScore": N, "feedback": "...", "strengths": ["..."], "improvements": ["..."] }`; } function buildDevilsAdvocatePrompt(positionId: string, response: string): string | null { const position = DEVILS_ADVOCATE_POSITIONS.find((p) => p.id === positionId); if (!position) return null; return `You are evaluating a devil's advocate exercise. The user was asked to argue AGAINST this widely-held or popular position: POSITION: "${position.position}" DOMAIN: ${position.domain} The user should produce the strongest counter-argument, not just nitpick. They should argue as if they genuinely believe the opposing view. USER'S RESPONSE: ${response} Score on three dimensions (0–10 each): - Argument Strength: How strong and substantive is the counter-argument? - Evidence: Does it use concrete data, examples, or principled reasoning? - Intellectual Honesty: Does the user acknowledge trade-offs rather than building a one-sided strawman? Respond ONLY in valid JSON (no markdown, no code fences): { "scores": { "argumentStrength": N, "evidence": N, "intellectualHonesty": N }, "overallScore": N, "feedback": "...", "strengths": ["..."], "improvements": ["..."] }`; } // --------------------------------------------------------------------------- // Route handler // --------------------------------------------------------------------------- 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 validTypes: ExerciseType[] = ["flaw-finder", "steelman", "devils-advocate"]; if (!body.exerciseType || !validTypes.includes(body.exerciseType)) { return NextResponse.json( { error: "exerciseType must be one of: flaw-finder, steelman, devils-advocate" }, { status: 400 }, ); } if (!body.response || typeof body.response !== "string" || body.response.trim().length < 20) { return NextResponse.json( { error: "response must be a non-empty string (minimum 20 characters)" }, { status: 400 }, ); } // Build prompt let prompt: string | null = null; let contentId: string = ""; let contentDescription: string = ""; if (body.exerciseType === "flaw-finder") { const b = body as FlawFinderBody; if (!b.passageId) { return NextResponse.json({ error: "passageId is required for flaw-finder" }, { status: 400 }); } prompt = buildFlawFinderPrompt(b.passageId, b.response); contentId = b.passageId; const passage = FLAW_FINDER_PASSAGES.find((p) => p.id === b.passageId); contentDescription = passage ? `Flaw Finder: ${passage.title}` : "Flaw Finder"; } else if (body.exerciseType === "steelman") { const b = body as SteelmanBody; if (!b.positionId) { return NextResponse.json({ error: "positionId is required for steelman" }, { status: 400 }); } prompt = buildSteelmanPrompt(b.positionId, b.response); contentId = b.positionId; const pos = STEELMAN_POSITIONS.find((p) => p.id === b.positionId); contentDescription = pos ? `Steelman: ${pos.position}` : "Steelman"; } else { const b = body as DevilsAdvocateBody; if (!b.positionId) { return NextResponse.json({ error: "positionId is required for devils-advocate" }, { status: 400 }); } prompt = buildDevilsAdvocatePrompt(b.positionId, b.response); contentId = b.positionId; const pos = DEVILS_ADVOCATE_POSITIONS.find((p) => p.id === b.positionId); contentDescription = pos ? `Devil's Advocate: ${pos.position}` : "Devil's Advocate"; } if (!prompt) { return NextResponse.json({ error: "Content not found" }, { status: 404 }); } // --- Call Claude (DEBATE framework for steelman / devils-advocate) --- let scored: ClaudeScoreResult; let debateLog: DebateScoreResult["debateLog"] | undefined; try { if (body.exerciseType === "steelman" || body.exerciseType === "devils-advocate") { const pos = body.exerciseType === "steelman" ? STEELMAN_POSITIONS.find((p) => p.id === (body as SteelmanBody).positionId) : DEVILS_ADVOCATE_POSITIONS.find((p) => p.id === (body as DevilsAdvocateBody).positionId); const debateResult = await runDebateScoring( body.exerciseType, pos!.position, pos!.domain, body.response, ); scored = { scores: debateResult.scores, overallScore: debateResult.overallScore, feedback: debateResult.feedback, strengths: debateResult.strengths, improvements: debateResult.improvements, }; debateLog = debateResult.debateLog; } else { // Flaw-finder: single-pass scoring (no debate) const message = await claude.messages.create({ model: "claude-haiku-4-5-20251001", max_tokens: 1024, messages: [{ role: "user", content: prompt! }], }); const text = message.content[0].type === "text" ? message.content[0].text : "{}"; scored = parseClaudeJson(text) as ClaudeScoreResult; } } catch (err) { return NextResponse.json( { error: "Failed to score response", 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: "critical-thinking" } } }, }); if (!user) { return NextResponse.json({ error: "No user found" }, { status: 404 }); } const criticalSkill = user.categorySkills[0]; if (!criticalSkill) { return NextResponse.json( { error: "Critical Thinking CategorySkill not found" }, { status: 500 }, ); } // --- XP calculation (with skill tree multiplier) --- const qualityScore = Math.min(1, Math.max(0, scored.overallScore / 10)); const { baseXp, maxQualityBonus } = EXERCISE_XP["critical-thinking"]; const isCriticalHit = rollCriticalHit(); const multiplierPercent = await getMultiplierPercent(prisma, userId, "critical-thinking"); 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: criticalSkill.currentXp + xpResult.totalXp, xpToNextLevel: criticalSkill.xpToNext, level: criticalSkill.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 --- let unlockResult = { unlocked: [] as string[], streakFreezesGranted: 0 }; await prisma.$transaction(async (tx) => { await tx.activity.create({ data: { userId, category: "critical-thinking", exerciseType: body.exerciseType, description: contentDescription, baseXp: xpResult.baseXp, qualityBonus: xpResult.qualityBonus, isCriticalHit: xpResult.isCriticalHit, totalXp: xpResult.totalXp, score: qualityScore, durationSecs: typeof body.durationSecs === "number" && body.durationSecs >= 0 ? Math.round(body.durationSecs) : null, metadata: JSON.stringify({ exerciseType: body.exerciseType, contentId, overallScore: scored.overallScore, scores: scored.scores, ...(debateLog && { debateLog }), }), }, }); 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: criticalSkill.id }, data: { totalXp: criticalSkill.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, "critical-thinking", 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({ exerciseType: body.exerciseType, scores: scored.scores, overallScore: scored.overallScore, feedback: scored.feedback, strengths: scored.strengths ?? [], improvements: scored.improvements ?? [], 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, ...(debateLog && { debateLog }), }); });