import type { EnvironmentSpeechModel, EnvironmentSpeechStatus } from "@t3tools/contracts";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

declare global {
  interface Window { voiceProof: { setPrePermission: () => void } }
}

test("A saved microphone stays labeled while permission hides device ids", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Voice notes", messages: ["first"], model: "default" });
  const model = { id: "scenario-speech", name: "Scenario speech model", description: "", size: 1_048_576, languages: ["en"], accuracy: 1, speed: 1, recommended: true, supportsStreaming: false, supportsLanguageDetection: true, supportsTranslation: false, active: false, state: "downloadable" } satisfies EnvironmentSpeechModel;
  let installed = false;
  await browser.route(/\/api\/voice\/status$/, (route) => route.fulfill({ json: { supported: true, state: installed ? "ready" : "missing-model", modelId: model.id, model: model.name, size: model.size, supportsStreaming: false, supportsTranslation: false, acceleration: "cpu", benchmarkTier: "cpu", modelUnloadTimeout: "never", gpuDevices: [] } satisfies EnvironmentSpeechStatus }));
  await browser.route(/\/api\/voice\/models(?:\?|$)/, (route) => route.fulfill({ json: { models: [installed ? { ...model, active: true, state: "installed" } : model] } }));
  await browser.route(/\/api\/voice\/models\/download$/, (route) => { installed = true; return route.fulfill({ json: { models: [{ ...model, active: true, state: "installed" }] } }); });
  await browser.addInitScript(() => {
    const media = navigator.mediaDevices;
    let prePermission = false;
    const fake = [
      { kind: "audioinput", deviceId: "f4db2", label: "Fake Audio Input 2" },
      { kind: "audioinput", deviceId: "f4db1", label: "Fake Audio Input 1" },
    ];
    Object.defineProperty(media, "enumerateDevices", { configurable: true, value: () => Promise.resolve(prePermission ? [{ kind: "audioinput", deviceId: "", label: "" }] : fake) });
    window.voiceProof = { setPrePermission: () => { prePermission = true; } };
  });
  await t3.open(thread);
  const threadPath = new URL(await browser.url()).pathname;
  const voice = screen.getByRole("button", "Start voice input");
  await voice.tap();
  await screen.getByRole("combobox", "Transcribe with").tap();
  await screen.getByRole("option").nth(1).tap();
  await app.open(threadPath);
  await voice.tap();
  await screen.getByRole("button", "Download model", { exact: true }).tap();
  await screen.getByText("Voice input is ready", { exact: true }).waitFor();
  const picker = screen.getByRole("combobox", "Microphone", { exact: true });
  await picker.tap();
  await screen.getByRole("option", "Fake Audio Input 2", { exact: true }).tap();
  await browser.evaluate(() => { window.voiceProof.setPrePermission(); navigator.mediaDevices.dispatchEvent(new Event("devicechange")); });
  await new Promise((resolve) => setTimeout(resolve, 200));
  await expect(picker).toHaveText("Fake Audio Input 2");
  await expect(screen.getByText("That microphone is unplugged. Pick another one.")).not.toBeVisible();
  await app.screenshot("saved-microphone-before-permission");
});
