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

test("Silent dictation restores the composer caret at its existing selection", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("dictation-demo");
  await t3.open();
  const issued = await runPromise(makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]));
  const headers = { authorization: `Bearer ${issued.stdout.trim()}`, "content-type": "application/json" };
  const modelId = "handy-computer/whisper-tiny.en-gguf";
  for (const action of ["download", "select"]) {
    const result = await fetch(`${app.baseUrl}/api/voice/models/${action}`, { method: "POST", headers, body: JSON.stringify({ modelId }) });
    if (!result.ok) throw new Error(`Speech model ${action}: ${result.status} ${await result.text()}`);
  }
  await browser.evaluate(async () => {
    const environment = await (await fetch("/.well-known/t3/environment")).json();
    localStorage.setItem("t3code:voice-audio-grant:v1", JSON.stringify({ id: "scenario-audio", destination: { kind: "environment", environmentId: environment.environmentId } }));
    return null;
  });
  await browser.reload();
  // A genuine silent MediaStream feeds the app's AudioWorklet and local transcription model.
  await browser.evaluate(() => {
    navigator.mediaDevices.getUserMedia = async () => {
      const context = new AudioContext();
      const source = context.createConstantSource();
      source.offset.value = 0;
      const destination = context.createMediaStreamDestination();
      source.connect(destination);
      source.start();
      await context.resume();
      return destination.stream;
    };
    return null;
  });
  const editor = screen.getByRole("textbox");
  await editor.tap();
  await browser.keyboard.type("Hello world draft");
  for (let i = 0; i < 6; i++) await browser.keyboard.press("ArrowLeft");
  await app.screenshot("before-dictation");
  await browser.keyboard.press("Control+Shift+D");
  await screen.getByRole("button", "Finish voice input", { exact: false }).waitFor({ state: "visible" });
  await browser.evaluate(() => new Promise<null>(resolve => setTimeout(() => resolve(null), 3500)));
  await browser.keyboard.press("Control+Shift+D");
  await screen.getByText("No speech heard", { exact: true }).waitFor({ state: "visible", timeout: 120000 });
  await app.screenshot("silent-dictation-finished");
  const focus = await browser.evaluate(() => ({ active: document.activeElement?.tagName, editorFocused: document.activeElement?.classList.contains("ProseMirror"), offset: window.getSelection()?.anchorOffset }));
  await browser.keyboard.type("X");
  await app.screenshot("typing-resumes");
  const text = await browser.evaluate(() => document.querySelector(".ProseMirror")?.textContent ?? "");
  console.log(JSON.stringify({ focusAfterDictation: focus, textAfterTyping: text }));
  expect({ editorFocused: focus.editorFocused, offset: focus.offset, text }).toEqual({ editorFocused: true, offset: 11, text: "Hello worldX draft" });
});
