import { describe, expect, test } from "bun:test";

import type { RawContentExpectations } from "../../../../../src/server/checker/expect/types";

import { checkContentExpectations, resolveContentExpectations } from "../../../../../src/server/checker/expect/content";

function checkTextRules(text: string, rawRules: RawContentExpectations, phase: string) {
  const resolved = resolveContentExpectations(rawRules);
  return checkContentExpectations(text, resolved, { path: phase, phase });
}

describe("checkTextRules", () => {
  test("无规则返回匹配成功", () => {
    const r = checkTextRules("hello", [], "stdout");
    expect(r.matched).toBe(true);
    expect(r.failure).toBeNull();
  });

  test("单条 contains 规则匹配成功", () => {
    const r = checkTextRules("build completed successfully", [{ contains: "completed" }], "stdout");
    expect(r.matched).toBe(true);
  });

  test("单条 contains 规则匹配失败", () => {
    const r = checkTextRules("build completed successfully", [{ contains: "failed" }], "stdout");
    expect(r.matched).toBe(false);
    expect(r.failure!.phase).toBe("stdout");
    expect(r.failure!.path).toBe("stdout[0]");
  });

  test("多条规则全部通过", () => {
    const r = checkTextRules(
      "version: 3.2.1, build: ok",
      [{ contains: "version" }, { regex: "\\d+\\.\\d+\\.\\d+" }],
      "stdout",
    );
    expect(r.matched).toBe(true);
  });

  test("第一条规则失败立即返回", () => {
    const r = checkTextRules("error occurred", [{ contains: "success" }, { contains: "error" }], "stdout");
    expect(r.matched).toBe(false);
    expect(r.failure!.phase).toBe("stdout");
    expect(r.failure!.path).toBe("stdout[0]");
  });

  test("stderr phase", () => {
    const r = checkTextRules("warning: deprecated", [{ contains: "warning" }], "stderr");
    expect(r.matched).toBe(true);
    expect(r.failure).toBeNull();
  });

  test("empty 操作符", () => {
    const r = checkTextRules("", [{ empty: true }], "stderr");
    expect(r.matched).toBe(true);
  });
});
