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

export async function GET() {
  try {
    const root = debugDirPath();
    let entries: string[] = [];
    try {
      entries = await readdir(root);
    } catch {
      return NextResponse.json({ runs: [] });
    }

    const runs = [];
    for (const id of entries) {
      const dir = path.join(root, id);
      const info = await stat(dir).catch(() => null);
      if (!info?.isDirectory()) continue;

      let manifest: {
        label?: string;
        startedAt?: string;
        steps?: Array<{ step?: string; at?: string; screenshot?: string }>;
      } = {};
      try {
        manifest = JSON.parse(await readFile(path.join(dir, "manifest.json"), "utf8"));
      } catch {
        // ignore
      }

      runs.push({
        id,
        label: manifest.label ?? id,
        startedAt: manifest.startedAt ?? info.mtime.toISOString(),
        stepCount: manifest.steps?.length ?? 0,
        lastStep: manifest.steps?.at(-1)?.step ?? null,
      });
    }

    runs.sort((a, b) => (a.startedAt < b.startedAt ? 1 : -1));
    return NextResponse.json({ runs: runs.slice(0, 30) });
  } catch (error) {
    const message = error instanceof Error ? error.message : "讀取 debug 紀錄失敗";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}