import { describe, expect, it } from "vitest";
import { normalizeAcpHistoryToSessionMessages } from "../src/dimsdk/core/acp-history-normalizer.ts";

describe("acp history normalizer", () => {
  it("extracts text content from mixed structured payloads", () => {
    const messages = [
      {
        role: "user",
        content: [
          { type: "text", text: "hello " },
          { type: "output_text", content: "world" },
        ],
      },
      {
        role: "assistant",
        content: { content: [{ type: "text", text: "done" }] },
      },
    ] as unknown as Parameters<typeof normalizeAcpHistoryToSessionMessages>[0];

    expect(normalizeAcpHistoryToSessionMessages(messages)).toEqual([
      { role: "user", content: "hello world" },
      { role: "assistant", content: "done" },
    ]);
  });

  it("normalizes tool call ids and preserves structured arguments", () => {
    const messages = [
      {
        role: "assistant",
        content: "",
        tool_calls: [
          {
            id: "call 1",
            type: "function",
            function: {
              name: "Read",
              arguments: { path: "/tmp/demo" },
              thoughtSignature: "sig-1",
            },
          },
        ],
        metadata: { originalEventType: "tool_call_end" },
      },
      {
        role: "tool",
        tool_call_id: "call 1",
        content: { ok: true },
        metadata: { error: true },
      },
    ] as const;

    expect(normalizeAcpHistoryToSessionMessages(messages)).toEqual([
      {
        role: "assistant",
        content: "",
        tool_calls: [
          {
            id: "call_1",
            type: "function",
            function: {
              name: "Read",
              arguments: { path: "/tmp/demo" },
              thoughtSignature: "sig-1",
            },
          },
        ],
      },
      {
        role: "tool",
        tool_call_id: "call_1",
        content: "{\"ok\":true}",
        isError: true,
      },
    ]);
  });

  it("drops trailing pending user input when requested", () => {
    const messages = [
      { role: "user", content: "kept" },
      { role: "assistant", content: "done" },
      { role: "user", content: "pending" },
    ] as const;

    expect(
      normalizeAcpHistoryToSessionMessages(messages, {
        dropTrailingPendingUserInput: true,
      }),
    ).toEqual([
      { role: "user", content: "kept" },
      { role: "assistant", content: "done" },
    ]);
  });
});
