import { readdir, readFile } from "node:fs/promises";
import path from "node:path";

export const runtime = "nodejs";

export async function GET() {
  try {
    const inputsDir = path.join(process.cwd(), "inputs");
    const files = await readdir(inputsDir);
    const policyFiles = files
      .filter((name) => /^evaluation_policy_v\d+\.\d+$/i.test(name))
      .sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }));

    if (policyFiles.length === 0) {
      return Response.json({ error: "No evaluation policy files found." }, { status: 404 });
    }

    const policies = await Promise.all(
      policyFiles.map(async (fileName) => {
        const policyPath = path.join(inputsDir, fileName);
        const raw = await readFile(policyPath, "utf-8");
        return JSON.parse(raw) as Record<string, unknown>;
      })
    );

    const defaultPolicy =
      policies.find(
        (policy) =>
          typeof policy.policyId === "string" &&
          policy.policyId.toLowerCase() === "evaluationpolicy#v1.0"
      ) ?? policies[0];
    const defaultPolicyId =
      typeof defaultPolicy.policyId === "string" ? defaultPolicy.policyId : undefined;

    return Response.json({ policies, defaultPolicyId });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unknown server error";
    return Response.json({ error: message }, { status: 500 });
  }
}
