/**
 * GET /api/pipelines/:id/schema
 *
 * Pipeline introspection for UI form rendering. Returns the
 * declared input fields of a workflow.
 *
 * `:id` here actually carries the workflow NAME (not a pipeline_run id);
 * the path segment must match the sibling `/api/pipelines/[id]/route.ts`
 * to satisfy Next.js routing (one slug name per path depth).
 *
 * Input source supports BOTH shapes (pipeline.yaml `input:` block):
 *   bug_id: "Bug id (numeric)"                  ← legacy: description only
 *   bug_id:                                       ← extended: full spec
 *     description: "Bug id"
 *     type: integer                              # string | integer | number | boolean | enum
 *     enum: [open, fixed]                        # only for type: enum
 *     required: true
 *     default: 0
 *     multiline: false                           # forces textarea
 *     label: "Bug ID"                            # display label
 *
 * Both forms are normalized to the same flat response so the UI
 * doesn't need a per-shape branch.
 */

import { NextResponse } from 'next/server';
import { listWorkflows, normalizeInputField } from '@/lib/pipeline';

export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const name = decodeURIComponent(id);
  const workflow = listWorkflows().find((w) => w.name === name);
  if (!workflow) {
    return NextResponse.json({ error: `pipeline "${name}" not found` }, { status: 404 });
  }

  const entries = Object.entries(workflow.input || {});
  const fields = entries.map(([key, spec]) => normalizeInputField(key, spec));

  // schema_version=2 when EVERY input uses the extended object form
  // (or the pipeline declares no inputs at all — nothing to render).
  // Any legacy string-form input → version 1. Lets clients (e.g. the
  // browser extension) gate strict schema-driven rendering on v2 only
  // and fall back to a "use Forge web" hint for v1.
  const schemaVersion = entries.every(([, spec]) => typeof spec === 'object' && spec !== null) ? 2 : 1;

  return NextResponse.json({
    name: workflow.name,
    description: workflow.description ?? null,
    schema_version: schemaVersion,
    input: fields,
  });
}
