/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Failed cloud transcription offers retry of the saved recording", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("voice-demo");
  const thread = await t3.thread({ project, title: "Voice notes", messages: ["first"] });
  await browser.addInitScript(() => {
    Object.defineProperty(navigator.mediaDevices, "getUserMedia", { configurable: true, value: async () => {
      const context = new AudioContext();
      const oscillator = context.createOscillator();
      oscillator.frequency.value = 440;
      const destination = context.createMediaStreamDestination();
      oscillator.connect(destination);
      oscillator.start();
      await context.resume();
      return destination.stream;
    }});
  });
  await t3.open("/settings/voice");
  await screen.getByRole("combobox", "Transcribe with").tap();
  await screen.getByRole("option", /OpenAI via/).tap();
  await screen.getByRole("textbox", "OpenAI API key", { exact: true }).fill("sk-invalid-voice-proof");
  await screen.getByRole("button", "Save and enable", { exact: true }).tap();
  await screen.getByText("OpenAI via Scenario", { exact: true }).waitFor();
  await t3.open(thread);
  await screen.getByRole("button", "Start voice input", { exact: true }).tap();
  await browser.evaluate(async () => {
    await new Promise(resolve => setTimeout(resolve, 7000));
    return null;
  });
  await screen.getByRole("button", "Finish voice input", { exact: true }).tap();
  await screen.getByText(/^(Voice input failed|Transcription failed)$/).waitFor();
  await app.screenshot("failed-transcription");
  const text = await browser.evaluate(() => document.body.innerText);
  expect(text).toContain("Transcription failed");
  await expect(screen.getByRole("button", "Retry transcription", { exact: true })).toBeVisible();
});
