import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { afterEach, describe, expect, it } from "vitest";
import { createRandomId } from "@best-agent/foundation";
import { LocalThreadStore } from "../core/thread-store.js";
import { AgentRuntime } from "./agent-runtime.js";

const storageRoots: string[] = [];

afterEach(() => {
  while (storageRoots.length > 0) {
    rmSync(storageRoots.pop() as string, { force: true, recursive: true });
  }
});

describe("AgentRuntime.resumeThread", () => {
  it("can resume only the tail items", async () => {
    const storageRoot = mkdtempSync(`${tmpdir()}/best-agent-runtime-tail-resume-`);
    storageRoots.push(storageRoot);

    const store = new LocalThreadStore({ storageRoot });
    const runtime = new AgentRuntime({ storageRoot, store });
    const thread = await store.createThread({ cwd: storageRoot, title: "tail resume" });
    const turnIds: string[] = [];

    for (let index = 0; index < 6; index += 1) {
      const turn = await store.createTurn({ threadId: thread.id });
      turnIds.push(turn.id);
      await store.appendItems([
        {
          createdAt: new Date(Date.UTC(2026, 0, 1, 0, 0, index)).toISOString(),
          id: createRandomId("item"),
          kind: "message",
          role: "user",
          text: `message ${index}`,
          threadId: thread.id,
          turnId: turn.id,
        },
      ]);
      await store.updateTurnStatus(turn.id, "completed");
    }

    try {
      const resumed = await runtime.resumeThread(thread.id, { itemLimit: 2 });

      expect(resumed.items.map((item) => (item.kind === "message" ? item.text : ""))).toEqual([
        "message 4",
        "message 5",
      ]);
      expect(resumed.turns.map((turn) => turn.id)).toEqual([turnIds[4], turnIds[5]]);
    } finally {
      await runtime.close();
    }
  });
});
