import { NextResponse } from "next/server";
import { readFile, readdir } from "fs/promises";
import path from "path";
import { debugDirPath } from "@/lib/threads-browser/debug";

export async function GET(
  _request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    if (id.includes("..") || id.includes("/")) {
      return NextResponse.json({ error: "無效的 run id" }, { status: 400 });
    }

    const dir = path.join(debugDirPath(), id);
    const manifest = JSON.parse(
      await readFile(path.join(dir, "manifest.json"), "utf8")
    );
    const files = (await readdir(dir)).filter((f) => f.endsWith(".png"));

    return NextResponse.json({ run: manifest, screenshots: files });
  } catch {
    return NextResponse.json({ error: "找不到 debug 紀錄" }, { status: 404 });
  }
}