import { beforeEach, describe, expect, it, vi } from "vitest";
import { initializeLogger } from "../../log.js";
import { MockWebSocket } from "./_mock_ws.js";
import { AdaptiveInterruptionDetector } from "./interruption_detector.js";
import { InterruptionStreamBase } from "./interruption_stream.js";
import { resolveEffectiveThreshold, wsMessageSchema } from "./ws_transport.js";
vi.mock("ws", async () => {
  const { MockWebSocket: MockWebSocket2 } = await import("./_mock_ws.js");
  return { default: MockWebSocket2, WebSocket: MockWebSocket2 };
});
initializeLogger({ pretty: false, level: "silent" });
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function waitFor(predicate, timeoutMs = 2e3) {
  const start = performance.now();
  while (!predicate()) {
    if (performance.now() - start > timeoutMs) {
      throw new Error("condition not met within timeout");
    }
    await sleep(5);
  }
}
function createDetector(opts = {}) {
  return new AdaptiveInterruptionDetector({
    baseUrl: "http://localhost:9999",
    apiKey: "test-key",
    apiSecret: "test-secret",
    ...opts
  });
}
async function captureSessionCreate(detector) {
  const stream = new InterruptionStreamBase(detector, {});
  try {
    await waitFor(() => MockWebSocket.instances.length > 0);
    const ws = MockWebSocket.instances[MockWebSocket.instances.length - 1];
    ws.simulateOpen();
    await waitFor(() => ws.sent.length > 0);
    return JSON.parse(String(ws.sent[0]));
  } finally {
    await stream.close();
  }
}
beforeEach(() => {
  MockWebSocket.instances.length = 0;
});
describe("session.create threshold", () => {
  it("omits threshold when not given", async () => {
    const payload = await captureSessionCreate(createDetector());
    expect("threshold" in payload.settings).toBe(false);
  });
  it("includes threshold when overridden", async () => {
    const payload = await captureSessionCreate(createDetector({ threshold: 0.7 }));
    expect(payload.settings.threshold).toBe(0.7);
  });
});
describe("session.created default_threshold parsing", () => {
  it("parses default_threshold", () => {
    const msg = wsMessageSchema.parse({ type: "session.created", default_threshold: 0.42 });
    expect(msg).toMatchObject({ type: "session.created", default_threshold: 0.42 });
  });
  it("treats default_threshold as optional", () => {
    const msg = wsMessageSchema.parse({ type: "session.created" });
    expect(msg.default_threshold ?? null).toBeNull();
  });
});
describe("resolveEffectiveThreshold", () => {
  it("prefers the user override", () => {
    expect(resolveEffectiveThreshold(0.7, 0.3)).toBe(0.7);
  });
  it("falls back to the server default", () => {
    expect(resolveEffectiveThreshold(void 0, 0.3)).toBe(0.3);
  });
  it("returns null when neither the user nor the server provides a value", () => {
    expect(resolveEffectiveThreshold(void 0, null)).toBeNull();
  });
});
//# sourceMappingURL=interruption_session_create.test.js.map