import { NextResponse } from "next/server";
import { getProjectConfigs, loadInitiatives } from "@/lib/autobuilder";

export const dynamic = "force-dynamic";

export async function GET(
  _req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const configs = await getProjectConfigs();
  const cfg = configs.find((c) => c.name === id);
  if (!cfg) return NextResponse.json({ error: "Project not found" }, { status: 404 });

  const initiatives = await loadInitiatives(cfg.autobuilderDir);

  // Sort: priority first (1=highest, 0=unset goes last), then pending before executed, then by id
  initiatives.sort((a, b) => {
    if (a.executed !== b.executed) return a.executed ? 1 : -1;
    const pa = a.priority || 999;
    const pb = b.priority || 999;
    if (pa !== pb) return pa - pb;
    return a.filename.localeCompare(b.filename, undefined, { numeric: true });
  });

  return NextResponse.json(initiatives);
}
