import { readFileSync } from "node:fs";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Dictionary spellings apply next to Chinese text in a real SenseVoice transcription", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("Speech dictionary demo");
  await t3.open("/settings/voice");
  await browser.evaluate(async (path) => {
    const post = async (route, body) => {
      const response = await fetch(route, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
      if (!response.ok) throw new Error(`${route}: ${response.status} ${await response.text()}`);
      return response.json();
    };
    await post("/api/voice/models/download", { modelId: "handy-computer/SenseVoiceSmall-gguf" });
    await post("/api/voice/models/select", { modelId: "handy-computer/SenseVoiceSmall-gguf" });
  }, process.env.VOICE_PROOF_MODEL!);
  await browser.reload();
  await screen.getByRole("combobox", "Transcribe with").tap();
  await screen.getByRole("option", "Scenario", { exact: true }).tap();
  await screen.getByRole("combobox", "Transcription language").tap();
  await screen.getByRole("option", "Chinese", { exact: true }).tap();
  await screen.getByRole("textbox", "Add a word or phrase to the shared dictionary").fill("React, GitHub, Kubernetes");
  await browser.keyboard.press("Enter");
  await screen.getByRole("button", "Add an alias for React").tap();
  await screen.getByRole("textbox", "Alias for React", { exact: true }).fill("瑞安特");
  await browser.keyboard.press("Enter");
  const audio = readFileSync(process.env.VOICE_PROOF_AUDIO!).toString("base64");
  await browser.evaluate(async (audio) => {
    const context = new AudioContext();
    const buffer = await context.decodeAudioData(Uint8Array.from(atob(audio), c => c.charCodeAt(0)).buffer);
    Object.defineProperty(navigator.mediaDevices, "getUserMedia", { configurable: true, value: async () => {
      await context.resume();
      const source = context.createBufferSource();
      source.buffer = buffer;
      source.loop = true;
      const destination = context.createMediaStreamDestination();
      source.connect(destination);
      source.start();
      return destination.stream;
    }});
  }, audio);
  await screen.getByRole("button", "Test model", { exact: true }).tap();
  await browser.evaluate(() => new Promise(resolve => setTimeout(() => resolve(true), 11000)));
  await screen.getByRole("button", "Finish voice input", { exact: true }).tap();
  // Wait for inference to finish before capturing or asserting its result.
  await screen.getByRole("button", "Test model", { exact: true }).waitFor({ state: "visible", timeout: 120000 });
  await screen.getByRole("status", "Test transcript").scrollIntoView();
  await app.screenshot("chinese-dictionary-transcript");
  await expect(screen.getByRole("status", "Test transcript")).toContainText("React");
  await expect(screen.getByRole("status", "Test transcript")).toContainText("Kubernetes");
  await expect(screen.getByRole("status", "Test transcript")).not.toContainText("瑞安特");
});
