import { describe, expect, it, vi } from "vitest";
import { createBackgroundRemovalProgress } from "./remove";

describe("background remover progress", () => {
  it("aggregates resource downloads without resetting the percentage", () => {
    const report = vi.fn();
    const progress = createBackgroundRemovalProgress(
      new Map([
        ["/models/isnet_quint8", 80],
        ["/onnxruntime-web/ort.wasm", 20],
      ]),
      report
    );

    progress("fetch:/models/isnet_quint8", 40, 80);
    progress("fetch:/models/isnet_quint8", 80, 80);
    progress("fetch:/onnxruntime-web/ort.wasm", 10, 20);
    progress("compute:decode", 0, 4);
    progress("compute:inference", 1, 4);
    progress("compute:encode", 4, 4);

    const percentages = report.mock.calls.map(
      ([value]) => value.percentage as number
    );
    expect(percentages).toEqual([...percentages].sort((a, b) => a - b));
    expect(percentages.at(-1)).toBe(100);
  });

  it("uses the full progress range when the model session is already loaded", () => {
    const report = vi.fn();
    const progress = createBackgroundRemovalProgress(new Map(), report);

    progress("compute:decode", 0, 4);
    progress("compute:inference", 1, 4);
    progress("compute:mask", 2, 4);
    progress("compute:encode", 4, 4);

    expect(report.mock.calls.map(([value]) => value.percentage)).toEqual([
      0, 25, 50, 100,
    ]);
  });
});
