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

export const runtime = 'nodejs'

/** GET — the prompt for writing every explanation in a set, in one call. */
export async function GET(req: Request) {
  if (!checkAgentAuth(req)) return new NextResponse('Unauthorized', { status: 401 })
  const setId = new URL(req.url).searchParams.get('setId')
  if (!setId) return NextResponse.json({ error: 'setId required' }, { status: 400 })

  const set = await db.itemSet.findUnique({
    where: { id: setId },
    include: { student: true, items: { orderBy: { position: 'asc' }, include: { item: true } } },
  })
  if (!set) return NextResponse.json({ error: 'not found' }, { status: 404 })

  // Only items still missing one, so a re-run is cheap and idempotent.
  const pending = set.items.filter((si) => !si.item.explanation)
  if (!pending.length) return new NextResponse(null, { status: 204 })

  return NextResponse.json({
    setId,
    prompt: buildExplanationPrompt({
      grade: set.student.grade,
      items: pending.map((si) => ({
        position: si.position + 1,
        stimulus: si.item.stimulus,
        prompt: si.item.prompt,
        choices: si.item.choices as { key: string; text: string }[] | null,
        answerKey: si.item.answerKey,
        rubricCriteria: si.item.rubricCriteria,
      })),
    }),
  })
}

/** POST — store them against their items. */
export async function POST(req: Request) {
  if (!checkAgentWrite(req)) return new NextResponse('Unauthorized', { status: 401 })

  let body: { setId?: string; explanations?: { position?: unknown; explanation?: unknown }[] }
  try {
    body = await req.json()
  } catch {
    return new NextResponse('Bad JSON', { status: 400 })
  }
  if (!body.setId || !Array.isArray(body.explanations)) {
    return NextResponse.json({ error: 'setId and explanations required' }, { status: 400 })
  }

  const set = await db.itemSet.findUnique({
    where: { id: body.setId },
    include: { items: true },
  })
  if (!set) return NextResponse.json({ error: 'not found' }, { status: 404 })

  let written = 0
  for (const e of body.explanations) {
    const position = Number(e.position) - 1 // the agent speaks 1-based
    const text = typeof e.explanation === 'string' ? e.explanation.trim() : ''
    if (!Number.isInteger(position) || !text) continue
    const si = set.items.find((x) => x.position === position)
    if (!si) continue
    await db.item.update({ where: { id: si.itemId }, data: { explanation: text } })
    written++
  }
  return NextResponse.json({ ok: true, written })
}
