import { describe, expect, it } from "vitest";

import { AdaptiveVad } from "@/integrations/voice-call-audio";

describe("AdaptiveVad", () => {
  it("adapts its silence window between 400 and 600ms", () => {
    const quiet = new AdaptiveVad();
    for (let i = 0; i < 20; i += 1) quiet.observe(0.005, i * 50);
    expect(quiet.silenceWindowMs).toBeGreaterThanOrEqual(400);
    expect(quiet.silenceWindowMs).toBeLessThanOrEqual(600);

    const noisy = new AdaptiveVad();
    for (let i = 0; i < 20; i += 1) noisy.observe(0.04, i * 50);
    expect(noisy.silenceWindowMs).toBeGreaterThanOrEqual(quiet.silenceWindowMs);
    expect(noisy.silenceWindowMs).toBeLessThanOrEqual(600);
  });

  it("ends a turn after speech followed by adaptive silence", () => {
    const vad = new AdaptiveVad();
    for (let i = 0; i < 10; i += 1) vad.observe(0.004, i * 50);
    expect(vad.observe(0.2, 500).speechStarted).toBe(true);
    let ended = false;
    let silenceDurationMs = 0;
    for (let t = 550; t <= 1200; t += 50) {
      const observation = vad.observe(0.001, t);
      ended ||= observation.turnEnded;
      silenceDurationMs ||= observation.silenceDurationMs;
    }
    expect(ended).toBe(true);
    expect(silenceDurationMs).toBeGreaterThanOrEqual(400);
    expect(silenceDurationMs).toBeLessThanOrEqual(600);
  });
});
