import { NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { checkAgentWrite } from '@/lib/agent-auth'
import { buildFeedbackPrompt } from '@/lib/prompts'

export const runtime = 'nodejs'

/**
 * GET  — the feedback prompt for a response, once it has been graded.
 * POST — the note the boy will read.
 *
 * Rule 7: this is a separate call from scoring, with a separate audience. The
 * agent runs it as its own transient session so "be encouraging" cannot leak
 * into the scoring pass, and the score's bluntness cannot leak into what a
 * ten-year-old reads.
 */
export async function GET(req: Request) {
  if (!checkAgentWrite(req)) return new NextResponse('Unauthorized', { status: 401 })

  const responseId = new URL(req.url).searchParams.get('responseId')
  if (!responseId) return NextResponse.json({ error: 'responseId required' }, { status: 400 })

  const response = await db.response.findUnique({
    where: { id: responseId },
    include: {
      student: true,
      setItem: { include: { item: true } },
      gradings: { where: { gradedBy: 'AI' }, orderBy: { pass: 'asc' }, take: 1 },
    },
  })
  if (!response) return NextResponse.json({ error: 'not found' }, { status: 404 })

  const graderNote = response.gradings[0]?.justification
  if (!graderNote) return NextResponse.json({ error: 'not graded yet' }, { status: 409 })

  const images = Array.isArray(response.imagePaths) ? (response.imagePaths as string[]) : []

  return NextResponse.json({
    prompt: buildFeedbackPrompt({
      grade: response.student.grade,
      itemPrompt: response.setItem.item.prompt,
      responseText: response.typedText,
      hasHandwrittenWork: images.length > 0,
      graderNote,
    }),
  })
}

export async function POST(req: Request) {
  if (!checkAgentWrite(req)) return new NextResponse('Unauthorized', { status: 401 })

  let body: { responseId?: string; feedback?: string }
  try {
    body = await req.json()
  } catch {
    return new NextResponse('Bad JSON', { status: 400 })
  }
  if (!body.responseId || typeof body.feedback !== 'string' || !body.feedback.trim()) {
    return NextResponse.json({ error: 'responseId and feedback required' }, { status: 400 })
  }

  try {
    await db.response.update({
      where: { id: body.responseId },
      data: { feedbackForStudent: body.feedback.trim().slice(0, 4000) },
    })
  } catch {
    return NextResponse.json({ error: 'not found' }, { status: 404 })
  }
  return NextResponse.json({ ok: true })
}
