import { describe, expect, it } from "vitest";
import {
  PLACE_DIAG_COLLECT_SNAPSHOT,
  PLACE_DIAG_SET_MARK,
  P0_PLACE_DIAG_INIT,
  P2_FETCH_HIJACK_INIT,
} from "@/workers/rpa/fix-place/place-diagnostic-init";
import { interpretPlaceDiagnostic } from "@/workers/rpa/fix-place/place-diagnostic-probe";

describe("place-diagnostic-init", () => {
  it("P0/P2 脚本为纯字符串", () => {
    for (const script of [
      P0_PLACE_DIAG_INIT,
      P2_FETCH_HIJACK_INIT,
      PLACE_DIAG_SET_MARK,
      PLACE_DIAG_COLLECT_SNAPSHOT,
    ]) {
      expect(typeof script).toBe("string");
      expect(script).not.toMatch(/__name|__assign/);
    }
    expect(P0_PLACE_DIAG_INIT).toContain("maps.event.addListener");
    expect(P0_PLACE_DIAG_INIT).toContain("fingerprintHandler");
    expect(P2_FETCH_HIJACK_INIT).toContain("axel/location/place");
  });
});

describe("interpretPlaceDiagnostic", () => {
  it("无监听器时提示 input gm 定位", () => {
    const lines = interpretPlaceDiagnostic(
      {
        ok: true,
        topology: { instanceCount: 0, instances: [], inputProbes: [], monkeyPatchInstances: 0, capturedHandlers: 0 },
        listeners: { total: 0, anyHasFetch: false, anyHasAxelPlace: false, rows: [] },
        handlerEvents: [],
        fetchLog: [],
      },
      "test",
    );
    expect(lines.some((l) => l.includes("无任何 place_changed 监听器"))).toBe(true);
  });

  it("有 handler 无 fetch 时提示 P2", () => {
    const lines = interpretPlaceDiagnostic(
      {
        ok: true,
        topology: { instanceCount: 1, instances: [], inputProbes: [], monkeyPatchInstances: 1, capturedHandlers: 1 },
        listeners: { total: 1, anyHasFetch: false, anyHasAxelPlace: false, rows: [] },
        handlerEvents: [{ type: "place_changed_handler", instanceId: "ac-1", getPlaceBefore: { place_id: "ChIJ_test", hasGeometry: true } }],
        fetchLog: [],
      },
      "test",
    );
    expect(lines.some((l) => l.includes("P2 无 place fetch"))).toBe(true);
  });
});
