import { describe, expect, it } from "vitest";
import {
  buildHermesRuntimeToolResultRequest,
  parseHermesToolPreviewArgs,
  readHermesToolArgsFromEvent,
  readHermesToolResultFromEvent,
} from "./tool-result-recovery";

describe("tool-result-recovery", () => {
  it("应从 JSON preview 中解析工具参数", () => {
    expect(
      parseHermesToolPreviewArgs('{"blockId":"block_1","text":"新的正文","mode":"replace"}', "doc_replace_range"),
    ).toEqual({
      blockId: "block_1",
      text: "新的正文",
      mode: "replace",
    });
  });

  it("应从 slash preview 中恢复 text 参数", () => {
    expect(parseHermesToolPreviewArgs("slash_run /rename doc-1 新标题", "slash_run")).toEqual({
      text: "/rename doc-1 新标题",
    });
  });

  it("应优先读取 Hermes 事件里直接给出的 argsJson", () => {
    expect(
      readHermesToolArgsFromEvent(
        {
          preview: "ignored",
          argsJson: { text: "/rename doc-1 直接参数" },
        },
        "slash_run",
      ),
    ).toEqual({
      text: "/rename doc-1 直接参数",
    });
  });

  it("应读取 Hermes 事件里直接给出的结构化 result", () => {
    expect(
      readHermesToolResultFromEvent({
        result: {
          ok: true,
          parsed: {
            command: "rename_doc",
          },
        },
      }),
    ).toEqual({
      ok: true,
      parsed: {
        command: "rename_doc",
      },
    });
  });

  it("应构造 mnote-web runtime tool result 请求体", () => {
    expect(
      buildHermesRuntimeToolResultRequest({
        userId: "user-1",
        tool: "doc_replace_range",
        argsJson: {
          blockId: "block_1",
          text: "新的正文",
          mode: "replace",
        },
        data: [
          {
            id: "block_1",
            type: "paragraph",
            content: "旧正文",
          },
        ],
        requestId: "req-1",
        traceId: "trace-1",
        target: {
          pageId: "doc-1",
          blockId: "block_1",
        },
      }),
    ).toEqual({
      kind: "tool",
      context: {
        deploymentId: null,
        projectId: null,
        workspaceId: null,
        requestId: "req-1",
        traceId: "trace-1",
        actor: {
          actorType: "user",
          actorId: "user-1",
          sessionId: null,
        },
        source: {
          channel: "next_route",
          client: "wolai-frontend",
        },
        tenantId: null,
        authToken: null,
        idempotencyKey: null,
        validateOnly: false,
        dryRun: false,
      },
      tool: {
        tool: "doc_replace_range",
        kind: "command",
        mode: "result",
        argsJson: {
          blockId: "block_1",
          text: "新的正文",
          mode: "replace",
        },
        target: {
          workspaceId: null,
          pageId: "doc-1",
          blockId: "block_1",
        },
        reason: null,
        refs: [],
      },
      data: [
        {
          id: "block_1",
          type: "paragraph",
          content: "旧正文",
        },
      ],
    });
  });
});
