// GET  /api/hail/engagements/[id]/blueprint  — read blueprint drafts
// POST /api/hail/engagements/[id]/blueprint  — synthesize the blueprint
//
// Synthesis designs the governance matrix, agent roster, classification
// framework, and a DRY-RUN setup package from the approved diagnostic. Nothing
// here mutates runtime configuration. Practitioner-gated.

import { getEngagement } from '../../../../../../lib/hail/engagements.js';
import { synthesizeBlueprint, getBlueprintDrafts } from '../../../../../../lib/hail/blueprint.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: getBlueprintDrafts(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 synthesizeBlueprint({ engagement_id: id, engine: body?.engine || undefined });
    return Response.json({ ok: true, result }, { status: 201 });
  } catch (err) {
    if (err?.code === 'no_diagnostic') return Response.json({ ok: false, error: 'no_diagnostic', message: err.message }, { status: 409 });
    if (err?.code === 'blueprint_invalid') return Response.json({ ok: false, error: 'blueprint_invalid', errors: err.errors }, { status: 422 });
    if (err?.code === 'setup_package_invalid') return Response.json({ ok: false, error: 'setup_package_invalid', errors: err.errors }, { status: 422 });
    if (err?.code === 'blueprint_agent_error') return Response.json({ ok: false, error: 'blueprint_agent_error', message: err.message }, { status: 502 });
    return errorResponse(err);
  }
}
