import { describe, expect, it } from "vitest";
import { SelectorGraph } from "@/workers/rpa/kernel/selector-graph";
import { RPAContext } from "@/workers/rpa/kernel/context";
import { isCargoStateReady } from "@/workers/rpa/kernel/state-engine";

function mockPage(): object {
  return {
    locator: () => ({
      filter: () => ({ nth: () => ({}) }),
      first: () => ({}),
    }),
    waitForTimeout: async () => undefined,
    url: () => "https://example.com",
  };
}

describe("SelectorGraph", () => {
  it("resolve widget selector", () => {
    const graph = new SelectorGraph();
    expect(graph.resolve("RPA_SELECTOR_QUOTE_WIDGET")).toBeTruthy();
  });

  it("specs 永不为 undefined", () => {
    const graph = new SelectorGraph();
    expect(graph.specs("NOT_A_REAL_KEY")).toEqual([]);
  });
});

describe("RPAContext", () => {
  it("scroll 时间戳存于实例", () => {
    const ctx = new RPAContext(mockPage() as never);
    expect(ctx.getWidgetScrollAt()).toBe(0);
    ctx.setWidgetScrollAt(123);
    expect(ctx.getWidgetScrollAt()).toBe(123);
  });

  it("runtime 与 exec 同源", () => {
    const ctx = new RPAContext(mockPage() as never);
    expect(ctx.runtime).toBe(ctx.exec);
  });
});

describe("isCargoStateReady", () => {
  it("托盘 interactive → ready", () => {
    expect(
      isCargoStateReady({
        phase: "interactive",
        mountedCargoFields: [{ placeholder: "需要几个托盘？", ariaLabel: null }],
        interactiveCargoFields: [
          { placeholder: "需要几个托盘？", ariaLabel: null },
        ],
        blockedCargoFields: [],
      }),
    ).toBe(true);
  });
});
