import { describe, expect, it } from "vitest";
import { validateProviderFinalAnswer } from "./provider-final-validator.js";

const toolEffects = new Map([
  ["read-file", "read"],
  ["shell", "execute"],
] as const);

describe("validateProviderFinalAnswer", () => {
  it("rejects execution success claims supported only by non-execution tool evidence", () => {
    const result = validateProviderFinalAnswer({
      messages: [
        { content: "Run the benchmark.", role: "user" },
        {
          content: "README contents",
          outcome: "success",
          role: "tool",
          toolCallId: "call_read",
          toolName: "read-file",
        },
      ],
      text: "The benchmark completed successfully.",
      toolEffects,
    });

    expect(result).toMatchObject({
      ok: false,
      observation: {
        code: "FINAL_ANSWER_UNSUPPORTED",
      },
    });
  });

  it("uses recent user intent when the latest user message is a continuation", () => {
    const result = validateProviderFinalAnswer({
      messages: [
        { content: "Run the test suite.", role: "user" },
        { content: "Continue.", role: "user" },
      ],
      text: "The tests passed.",
      toolEffects,
    });

    expect(result).toMatchObject({
      ok: false,
      observation: {
        code: "FINAL_ANSWER_UNSUPPORTED",
      },
    });
  });

  it("uses the turn objective when user messages only contain a continuation", () => {
    const result = validateProviderFinalAnswer({
      messages: [{ content: "Continue.", role: "user" }],
      objective: "Run the test suite.",
      text: "The tests passed.",
      toolEffects,
    });

    expect(result).toMatchObject({
      ok: false,
      observation: {
        code: "FINAL_ANSWER_UNSUPPORTED",
      },
    });
  });

  it("allows execution success claims with successful execution evidence", () => {
    const result = validateProviderFinalAnswer({
      messages: [
        { content: "Run the tests.", role: "user" },
        {
          content: "Tests passed.",
          outcome: "success",
          role: "tool",
          toolCallId: "call_shell",
          toolName: "shell",
        },
      ],
      text: "The tests completed successfully.",
      toolEffects,
    });

    expect(result).toEqual({ ok: true });
  });

  it("does not treat running a named non-execution tool as test evidence intent", () => {
    const result = validateProviderFinalAnswer({
      messages: [{ content: "Run the healthy heartbeat tool.", role: "user" }],
      text: "Healthy heartbeat tool completed.",
      toolEffects,
    });

    expect(result).toEqual({ ok: true });
  });
});
