import { describe, expect, it } from "vitest";
import { metricStatistics, summarizeBenchmarkSamples } from "./statistics";
import type { BenchmarkWorkerSample } from "./analysis.types";

function sample(
  compileMs: number,
  overrides: Partial<BenchmarkWorkerSample> = {},
): BenchmarkWorkerSample {
  return {
    accepted: true,
    effectiveFlags: "g",
    subjectBytes: 10,
    subjectUtf16: 10,
    compileMs,
    firstMatchMs: compileMs + 1,
    allMatchesMs: compileMs + 2,
    replacementMs: compileMs + 3,
    throughputBytesPerSecond: 100 / (compileMs + 1),
    matchCount: 1,
    matched: true,
    matchCollectionTruncated: false,
    replacementOutputUtf16: 10,
    ...overrides,
  };
}

describe("analysis statistics", () => {
  it("computes a conventional median and nearest-rank p95", () => {
    expect(metricStatistics([4, 1, 3, 2])).toEqual({
      count: 4,
      minimum: 1,
      median: 2.5,
      p95: 4,
      maximum: 4,
    });
    expect(
      metricStatistics(Array.from({ length: 100 }, (_, index) => index + 1))
        ?.p95,
    ).toBe(95);
  });

  it("ignores absent, negative and non-finite measurements", () => {
    expect(
      metricStatistics([
        undefined,
        Number.NaN,
        -1,
        0,
        Number.POSITIVE_INFINITY,
      ]),
    ).toEqual({
      count: 1,
      minimum: 0,
      median: 0,
      p95: 0,
      maximum: 0,
    });
    expect(metricStatistics([])).toBeUndefined();
  });

  it("summarizes only measurements actually produced by the worker", () => {
    const summary = summarizeBenchmarkSamples([
      sample(1),
      sample(3, {
        replacementMs: undefined,
        replacementSkippedReason: "bounded output estimate",
      }),
    ]);

    expect(summary.compileMs?.median).toBe(2);
    expect(summary.replacementMs).toEqual(
      expect.objectContaining({ count: 1, median: 4 }),
    );
  });
});
