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 { processEndOfDay } from "@/lib/streak"; import { buildFinalSummaryPrompt, aggregateScores, determineFinalWinner, type RoundJudgement, type FinalJudgement, } from "@/lib/debate/judge"; import { withApiError } from "@/lib/api-error"; interface SummaryBody { topic: string; opponentName: string; opponentId: string; opponentDifficulty: "easy" | "medium" | "hard"; rounds: RoundJudgement[]; totalRounds: number; userSide: "pro" | "con"; durationSecs?: number; userId?: number; } interface ClaudeFinalResponse { overallAnalysis: string; userStrengths: string[]; userWeaknesses: string[]; suggestions: string[]; } /** * POST /api/debate/summary * * After all rounds are judged, generates a final summary and persists XP. */ 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: SummaryBody; try { body = await request.json(); } catch { return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); } if (!body.topic || typeof body.topic !== "string") { return NextResponse.json({ error: "topic is required" }, { status: 400 }); } if (!body.opponentName || typeof body.opponentName !== "string") { return NextResponse.json({ error: "opponentName is required" }, { status: 400 }); } if (!Array.isArray(body.rounds) || body.rounds.length === 0) { return NextResponse.json({ error: "rounds must be a non-empty array" }, { status: 400 }); } // --- Compute scores --- const scores = aggregateScores(body.rounds); const winner = determineFinalWinner(body.rounds); // --- Generate final analysis via Claude --- let finalAnalysis: ClaudeFinalResponse; try { const prompt = buildFinalSummaryPrompt( body.topic, body.rounds, body.opponentName, ); const message = await claude.messages.create({ model: "claude-haiku-4-5-20251001", max_tokens: 2048, messages: [{ role: "user", content: prompt }], }); const text = message.content[0].type === "text" ? message.content[0].text : "{}"; finalAnalysis = parseClaudeJson(text); } catch { // Non-fatal: use fallback analysis finalAnalysis = { overallAnalysis: "The debate has concluded.", userStrengths: [], userWeaknesses: [], suggestions: [], }; } // --- Quality score: user avg / 10, clamped [0, 1] --- const qualityScore = Math.min(1, Math.max(0, scores.userAvg / 10)); // --- Difficulty bonus: harder opponents → better quality multiplier --- const difficultyWeight: Record = { easy: 0.8, medium: 1.0, hard: 1.2, }; const diffWeight = difficultyWeight[body.opponentDifficulty ?? "medium"] ?? 1.0; const adjustedQuality = Math.min(1, qualityScore * diffWeight); // --- XP calculation --- 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 }, ); } // Debate XP uses the critical-thinking config, scaled by number of rounds const { baseXp, maxQualityBonus } = EXERCISE_XP["critical-thinking"]; const roundMultiplier = body.rounds.length; const isCriticalHit = rollCriticalHit(); const multiplierPercent = await getMultiplierPercent(prisma, userId, "critical-thinking"); const xpResult = calculateXpGain({ baseXp: baseXp * roundMultiplier, qualityScore: adjustedQuality, maxQualityBonus: maxQualityBonus * roundMultiplier, 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, }); const newTitle = getTitleForLevel(userLevelResult.newLevel); const titleChanged = newTitle !== user.title; // --- Streak --- await processEndOfDay(userId); // --- Daily log --- 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: "debate", description: `Debate: ${body.topic} (vs ${body.opponentName}, ${body.rounds.length} rounds)`, baseXp: xpResult.baseXp, qualityBonus: xpResult.qualityBonus, isCriticalHit: xpResult.isCriticalHit, totalXp: xpResult.totalXp, score: adjustedQuality, durationSecs: typeof body.durationSecs === "number" && body.durationSecs >= 0 ? Math.round(body.durationSecs) : null, metadata: JSON.stringify({ exerciseType: "debate", opponentId: body.opponentId, opponentName: body.opponentName, opponentDifficulty: body.opponentDifficulty, topic: body.topic, userSide: body.userSide, roundCount: body.rounds.length, winner, userAvgScore: scores.userAvg, opponentAvgScore: scores.opponentAvg, }), }, }); 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, }, }); 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, }, }); } }); // --- Build final judgement response --- const finalJudgement: FinalJudgement = { rounds: body.rounds, userTotalScore: scores.userTotal, opponentTotalScore: scores.opponentTotal, winner, overallAnalysis: finalAnalysis.overallAnalysis ?? "The debate has concluded.", userStrengths: finalAnalysis.userStrengths ?? [], userWeaknesses: finalAnalysis.userWeaknesses ?? [], suggestions: finalAnalysis.suggestions ?? [], }; return NextResponse.json({ judgement: finalJudgement, xp: { baseXp: xpResult.baseXp, totalXp: xpResult.totalXp, qualityBonus: xpResult.qualityBonus, multiplierBonus: xpResult.multiplierBonus, multiplierPercent, isCriticalHit: xpResult.isCriticalHit, }, qualityScore: adjustedQuality, 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, }); });