// GET /api/marketplace/open-design?kind=skill|design-system|template|craft|prompt-template&scenario=&q=
//
// Returns the vendored Open Design catalog from workspace/skills/open-design/.
// Read-only. Powers the marketplace open-design surface and any future
// agent-readable browser.

import { listAllEntries, isVendored, getCommit, openDesignRoot, readEntryContents } from '../../../../lib/open-design.js';
import path from 'node:path';

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

const ALLOWED_KINDS = new Set(['skill', 'design-system', 'template', 'craft', 'prompt-template']);

export async function GET(request) {
  const url = new URL(request.url);
  const kind = url.searchParams.get('kind') || undefined;
  const scenario = url.searchParams.get('scenario') || undefined;
  const query = url.searchParams.get('q') || undefined;
  const slug = url.searchParams.get('slug') || undefined;
  const includeBody = url.searchParams.get('include_body') === '1';

  if (kind && !ALLOWED_KINDS.has(kind)) {
    return Response.json({ error: `unknown kind: ${kind}` }, { status: 400 });
  }
  if (!isVendored()) {
    return Response.json({
      vendored: false,
      reason: 'Run `npm run vendor:open-design` to populate workspace/skills/open-design/.',
      items: [],
    });
  }

  let items = listAllEntries({ kind, scenario, query });
  if (slug) {
    items = items.filter(i => i.slug === slug);
  }

  if (includeBody) {
    items = items.map(item => {
      const body = readEntryContents(item);
      return { ...item, body: body ? body.slice(0, 32 * 1024) : null };
    });
  }

  return Response.json({
    vendored: true,
    commit: getCommit(),
    root: path.relative(process.cwd(), openDesignRoot()),
    count: items.length,
    items,
  });
}
