import { mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import type { ACPMessage } from "../src/dimsdk/core/acp.ts";
import { createConversationImageResolver } from "../src/dimsdk/core/store/resolve-conversation-images.ts";

const tempDirs: string[] = [];

afterEach(async () => {
  await Promise.all(
    tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })),
  );
});

describe("resolve conversation images", () => {
  it("resolves the latest user markdown image link into structured content", async () => {
    const dir = await mkdtemp(path.join(os.tmpdir(), "best-agent-image-"));
    tempDirs.push(dir);
    const imagePath = path.join(dir, "demo.png");
    await writeFile(imagePath, "not-a-real-png");

    const conversation: ACPMessage[] = [
      { role: "assistant", content: "old" },
      {
        role: "user",
        content: `before ![demo](${imagePath}) after`,
      },
    ];

    const resolveConversationImages = createConversationImageResolver({
      config: {
        modelCapabilities: { vision: true },
      },
    });
    await resolveConversationImages(conversation);

    expect(conversation[1]?.content).toEqual([
      { type: "text", text: "before !" },
      {
        type: "image",
        data: Buffer.from("not-a-real-png").toString("base64"),
        mimeType: "image/png",
      },
      { type: "text", text: " after" },
    ]);
  });

  it("skips image resolution when the active model has no vision capability", async () => {
    const conversation: ACPMessage[] = [
      {
        role: "user",
        content: "![demo](/tmp/demo.png)",
      },
    ];

    const resolveConversationImages = createConversationImageResolver({
      config: {
        modelCapabilities: { vision: false },
      },
    });
    await resolveConversationImages(conversation);

    expect(conversation[0]?.content).toBe("![demo](/tmp/demo.png)");
  });
});
