import { describe, expect, it } from "vitest";
import {
  diffHumanRpaNetwork,
  summarizeNetwork,
  type NetworkEvent,
} from "@/scripts/human-commit-baseline/network-diff";

const humanSample: NetworkEvent[] = [
  {
    ts: 100,
    iso: "",
    phase: "page_loaded",
    kind: "request",
    method: "POST",
    url: "https://services.mothership.com/axel/location/search",
    isLocationSearch: true,
  },
  {
    ts: 200,
    iso: "",
    phase: "page_loaded",
    kind: "response",
    method: "POST",
    url: "https://services.mothership.com/axel/location/search",
    status: 200,
    isLocationSearch: true,
  },
  {
    ts: 900,
    iso: "",
    phase: "page_loaded",
    kind: "request",
    method: "GET",
    url: "https://services.mothership.com/axel/location/place/ChIJabc",
    isPlaceCommit: true,
  },
  {
    ts: 1100,
    iso: "",
    phase: "page_loaded",
    kind: "response",
    method: "GET",
    url: "https://services.mothership.com/axel/location/place/ChIJabc",
    status: 200,
    isPlaceCommit: true,
  },
];

const rpaMissingPlace: NetworkEvent[] = [
  {
    ts: 100,
    iso: "",
    phase: "rpa_pickup",
    kind: "request",
    method: "POST",
    url: "https://services.mothership.com/axel/location/search",
    isLocationSearch: true,
  },
  {
    ts: 200,
    iso: "",
    phase: "rpa_pickup",
    kind: "response",
    method: "POST",
    url: "https://services.mothership.com/axel/location/search",
    status: 200,
    isLocationSearch: true,
  },
];

describe("network-diff", () => {
  it("真人 sample 识别 search→place 完整链", () => {
    const s = summarizeNetwork(humanSample, "human");
    expect(s.placeGet200).toBe(1);
    expect(s.chains[0]?.complete).toBe(true);
    expect(s.chains[0]?.gapSearchResponseToPlaceRequestMs).toBe(700);
  });

  it("RPA 缺 place 时 verdict=RPA_MISSING_PLACE", () => {
    const humanFull = [...humanSample, ...humanSample.map((e, i) => ({ ...e, ts: e.ts + 2000 + i }))];
    const d = diffHumanRpaNetwork(humanFull, rpaMissingPlace, "human1", "rpa1");
    expect(d.verdict).toBe("RPA_MISSING_PLACE");
    expect(d.gaps.some((g) => g.includes("place"))).toBe(true);
  });
});
