import { NextResponse } from 'next/server'
import { checkAgentWrite } from '@/lib/agent-auth'
import { recordAiGrading } from '@/lib/grading-run'

export const runtime = 'nodejs'

/**
 * POST /api/agent/grade — one grading pass for one response.
 *
 * The agent supplies numbers; the server decides whether they may be recorded.
 * recordAiGrading verifies the rubric version and hash the agent echoes back,
 * rejects dimensions that do not belong to the item's construct, and measures
 * pass-to-pass disagreement itself.
 */
export async function POST(req: Request) {
  if (!checkAgentWrite(req)) return new NextResponse('Unauthorized', { status: 401 })

  let body: {
    responseId?: string
    pass?: number
    scores?: { dimensionCode?: string; value?: number; justification?: string }[]
    overallNote?: string
    rubricVersion?: string
    rubricHash?: string
    promptVersion?: string
    modelId?: string
    raw?: unknown
  }
  try {
    body = await req.json()
  } catch {
    return new NextResponse('Bad JSON', { status: 400 })
  }

  const { responseId, pass, scores } = body
  if (!responseId || typeof responseId !== 'string') {
    return NextResponse.json({ error: 'responseId required' }, { status: 400 })
  }
  if (pass !== 1 && pass !== 2) {
    return NextResponse.json({ error: 'pass must be 1 or 2' }, { status: 400 })
  }
  if (!Array.isArray(scores) || scores.length === 0) {
    return NextResponse.json({ error: 'scores required' }, { status: 400 })
  }
  if (!body.rubricVersion || !body.rubricHash || !body.promptVersion || !body.modelId) {
    return NextResponse.json(
      { error: 'rubricVersion, rubricHash, promptVersion and modelId are all required' },
      { status: 400 },
    )
  }

  try {
    await recordAiGrading({
      responseId,
      pass,
      scores: scores.map((s) => ({
        dimensionCode: String(s.dimensionCode ?? ''),
        value: Number(s.value),
        justification: s.justification ?? null,
      })),
      overallNote: String(body.overallNote ?? ''),
      rubricVersion: body.rubricVersion,
      rubricHash: body.rubricHash,
      promptVersion: body.promptVersion,
      modelId: body.modelId,
      raw: body.raw,
    })
  } catch (err) {
    return NextResponse.json(
      { error: err instanceof Error ? err.message : 'failed to record' },
      { status: 400 },
    )
  }

  return NextResponse.json({ ok: true })
}
