import { NextRequest, NextResponse } from "next/server"; import { withApiError, ApiError } from "@/lib/api-error"; import { resolveProblem } from "@/lib/coding/store"; import { gradeCodeReview, gradeArchitecture } from "@/lib/coding/grade"; import { judgeWritten } from "@/lib/coding/judge"; import { awardCodingXp } from "@/lib/coding/award"; import { isWrittenProblem, type CodingDifficulty } from "@/lib/coding/types"; import { isLlmAvailable } from "@/lib/claude"; import type { CodeReviewVerdict, ArchitectureVerdict } from "@/lib/coding/grade"; interface SubmitWrittenBody { instanceId?: string; answer?: string; durationSecs?: number; userId?: number; } /** * POST /api/coding/submit-written * Body: { instanceId, answer, durationSecs? } * * Grades a written answer (code-review or architecture) with the LLM-as-judge * (or the offline heuristic when no API key is configured). Awards "written" * XP — separate from code XP — when the answer is judged correct. */ export const POST = withApiError(async (request: NextRequest) => { let body: SubmitWrittenBody; try { body = await request.json(); } catch { throw new ApiError(400, "Invalid JSON body"); } const { instanceId, answer, durationSecs } = body; const userId = body.userId ?? 1; if (!instanceId || typeof answer !== "string" || answer.trim().length === 0) { throw new ApiError(400, "instanceId and a non-empty answer are required"); } const problem = resolveProblem(instanceId); if (!problem) { throw new ApiError(404, "Problem not found (it may have expired — regenerate it)."); } if (!isWrittenProblem(problem)) { throw new ApiError(400, "This problem type is graded by running code, not a written answer."); } // AI judge when any LLM is reachable for this request (the visitor's HF // token, an env HF token, or an Anthropic key); else the offline heuristic. const useAI = isLlmAvailable(); const judgement = await judgeWritten(problem, answer, { useAI }); const grade = problem.type === "code-review" ? gradeCodeReview( problem.issues.length, judgement.verdict as CodeReviewVerdict, ) : gradeArchitecture( problem.rubric, judgement.verdict as ArchitectureVerdict, ); // Build hints about what a strong answer should have covered (post-submit). const expectations = problem.type === "code-review" ? problem.issues.map((i) => ({ id: i.id, title: i.title, severity: i.severity })) : problem.rubric.map((p) => ({ id: p.id, point: p.point })); const verdictDetail = problem.type === "code-review" ? { identified: (judgement.verdict as CodeReviewVerdict).identifiedIssueIds } : { covered: (judgement.verdict as ArchitectureVerdict).coveredPointIds }; const baseResponse = { correct: grade.isCorrect, qualityScore: grade.qualityScore, gradedBy: judgement.usedAI ? "llm-judge" : "heuristic", feedback: judgement.feedback, expectations, verdict: verdictDetail, }; if (!grade.isCorrect) { return NextResponse.json({ ...baseResponse, awarded: false, message: "Not quite — review the expected points and try again.", }); } const award = await awardCodingXp({ userId, exerciseType: "written", description: `Solved ${problem.difficulty} ${problem.type} "${problem.title}" (written)`, qualityScore: grade.qualityScore, difficulty: problem.difficulty as CodingDifficulty, durationSecs, metadata: { problemId: problem.id, problemType: problem.type, language: problem.language, difficulty: problem.difficulty, gradedBy: baseResponse.gradedBy, kind: "written", }, }); return NextResponse.json({ ...baseResponse, awarded: true, ...award, message: award.isCriticalHit ? "Critical Hit! Strong written answer!" : "Correct — written answer accepted!", }); });