// GET  /api/hail/engagements/[id]/diagnostic  — read current diagnostic drafts
// POST /api/hail/engagements/[id]/diagnostic  — synthesize the diagnostic
//
// Synthesis reads the engagement's interview responses through the engine
// projection (restricted content masked for cloud engines), writes the
// operating-model records, and renders the three artifacts. Practitioner-gated.

import { getEngagement } from '../../../../../../lib/hail/engagements.js';
import { synthesizeDiagnostic, getDiagnosticDrafts } from '../../../../../../lib/hail/diagnostic.js';
import { requirePractitioner, errorResponse } from '../../../guard.js';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function GET(req, { params }) {
  const { id } = await params;
  try {
    await requirePractitioner(req);
    if (!getEngagement(id)) return Response.json({ error: 'engagement_not_found' }, { status: 404 });
    return Response.json({ drafts: getDiagnosticDrafts(id) });
  } catch (err) {
    return errorResponse(err);
  }
}

export async function POST(req, { params }) {
  const { id } = await params;
  let body = {};
  try { body = await req.json(); } catch { /* body optional */ }
  try {
    await requirePractitioner(req);
    if (!getEngagement(id)) return Response.json({ error: 'engagement_not_found' }, { status: 404 });
    const result = await synthesizeDiagnostic({
      engagement_id: id,
      engine: body?.engine || undefined,
    });
    return Response.json({ ok: true, result }, { status: 201 });
  } catch (err) {
    if (err?.code === 'diagnostic_invalid') {
      return Response.json({ ok: false, error: 'diagnostic_invalid', errors: err.errors }, { status: 422 });
    }
    if (err?.code === 'diagnostic_agent_error') {
      return Response.json({ ok: false, error: 'diagnostic_agent_error', message: err.message }, { status: 502 });
    }
    return errorResponse(err);
  }
}
