import { describe, expect, it } from "vitest";
import {
  deriveSessionLastMessagePreviewFromMessages,
  deriveSessionLastUserMessageFromMessages,
  deriveSessionSummaryFromMessages,
  deriveSessionTitleFromMessages,
  messagePreviewText,
} from "../src/dimsdk/core/sessions.ts";

describe("dimsdk session title/summary", () => {
  it("extracts text from array content blocks", () => {
    const messages = [
      { role: "user", content: [{ type: "text", text: "hello" }, { type: "text", text: "world" }] },
    ];

    expect(deriveSessionTitleFromMessages(messages)).toContain("hello world");
    expect(deriveSessionSummaryFromMessages(messages)).toContain("hello world");
  });

  it("strips leading focus_files block from derived title/summary", () => {
    const messages = [{ role: "user", content: `[cli.mjs](/x/y/z) hi` }];

    expect(deriveSessionTitleFromMessages(messages)).toContain("hi");
    expect(deriveSessionTitleFromMessages(messages)).not.toContain("focus_files");
    expect(deriveSessionSummaryFromMessages(messages)).toContain("hi");
    expect(deriveSessionSummaryFromMessages(messages)).not.toContain("focus_files");
  });

  it("extracts assistant markdown and tool output previews", () => {
    expect(messagePreviewText({
      role: "assistant",
      parts: [
        { type: "status", text: "working" },
        { type: "markdown", markdown: "done" },
      ],
    })).toBe("done");

    expect(messagePreviewText({
      role: "tool",
      result: {
        output: "tool result",
      },
    })).toBe("tool result");
  });

  it("derives last user and last message previews from typed message shapes", () => {
    const messages = [
      { role: "user", content: [{ type: "text", text: "first prompt" }] },
      { role: "assistant", parts: [{ type: "markdown", markdown: "assistant reply" }] },
      { role: "tool", result: { output: "tool output" } },
      { role: "user", content: { text: "latest prompt" } },
    ];

    expect(deriveSessionLastUserMessageFromMessages(messages)).toBe("latest prompt");
    expect(deriveSessionLastMessagePreviewFromMessages(messages)).toBe("latest prompt");
  });
});
