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

// Synthetic microphone only; recording, speech inference and citation saving are real.
const wav = readFileSync(process.env.T3_CITATION_SPEECH_WAV ?? new URL("./speech.wav", import.meta.url)).toString("base64");
test("Clicking outside a dictated citation saves its comment", WEB, async ({t3, app, browser, screen}) => {
  await browser.addInitScript((audio) => {
    Object.defineProperty(navigator.mediaDevices, "getUserMedia", {value: async () => {
      const context = new AudioContext();
      await context.resume();
      const bytes = Uint8Array.from(atob(audio), c => c.charCodeAt(0));
      const buffer = await context.decodeAudioData(bytes.buffer);
      const source = context.createBufferSource();
      source.buffer = buffer;
      const destination = context.createMediaStreamDestination();
      source.connect(destination);
      source.start();
      return destination.stream;
    }});
    Object.defineProperty(navigator.mediaDevices, "enumerateDevices", {value: async () => [{kind:"audioinput", deviceId:"synthetic", groupId:"synthetic", label:"Synthetic speech microphone", toJSON() {return {};}}]});
  }, wav);
  const project = await t3.project("citation-demo");
  const thread = await t3.thread({project, title:"Citation voice comments", messages:["Show the completed change"], model:"showcase"});
  await t3.open("/settings/voice");
  await screen.getByRole("combobox", "Transcribe with").tap();
  await screen.getByRole("option", "Scenario", {exact:true}).tap();
  await screen.getByRole("switch", "Silence filtering", {exact:true}).tap();
  await screen.getByRole("searchbox", "Search transcription models").fill("Canary 180M Flash");
  await screen.getByRole("button", "Download", {exact:true}).tap();
  await screen.getByRole("button", "Use model", {exact:true}).tap({timeout:180000});
  await t3.open(thread);
  const results: string[] = [];
  for (const [index, bullet] of ["Reads the manifest first", "Asks before it writes", "Streams a terminal result"].entries()) {
    const item = screen.getByText(bullet, {exact:true});
    await item.tap();
    await browser.evaluate((text) => {
      const element = [...document.querySelectorAll('[data-assistant-citation-source] li')].find(e => e.textContent === text);
      if (!element) throw new Error("Missing assistant bullet");
      const range = document.createRange(); range.selectNodeContents(element);
      const selection = window.getSelection(); selection?.removeAllRanges(); selection?.addRange(range);
      document.dispatchEvent(new Event("selectionchange"));
      return null;
    }, bullet);
    await screen.getByRole("button", "Cite selection in composer", {exact:true}).tap();
    const editor = browser.locator('[data-citation-comment-editor]');
    await editor.getByRole("button", "Start voice input", {exact:true}).tap();
    await screen.getByRole("button", "Finish voice input", {exact:true}).waitFor();
    await browser.evaluate(async () => {await new Promise(r => setTimeout(r,9500)); return null;});
    await app.screenshot(`case-${index}-recording`);
    if (index !== 1) {
      await screen.getByRole("button", "Finish voice input", {exact:true}).tap();
      if (index === 0) {
        await editor.getByRole("button", "Start voice input", {exact:true}).waitFor({timeout:90000});
      } else {
        await browser.evaluate(async () => {await new Promise(r => setTimeout(r,150)); return null;});
      }
    }
    if (index === 2) await app.screenshot("case-2-transcribing-before-outside");
    // Same empty timeline-header position in every case, outside the citation popover.
    await browser.locator('[data-chat-header]').tap({position:{x:400,y:15}});
    await browser.evaluate(async () => {await new Promise(r => setTimeout(r,15000)); return null;});
    // Reopen the saved citation comment so the final text is readable in the capture.
    await browser.locator('[data-citation-comment-trigger]').nth(index).tap();
    // Let the popover opening transition settle so the text is legible.
    await browser.evaluate(async () => {await new Promise(r => setTimeout(r,500)); return null;});
    await app.screenshot(`case-${index}-saved-comment`);
    results.push(await browser.evaluate(() => (document.querySelector('[data-citation-comment-editor] textarea') as HTMLTextAreaElement)?.value ?? ""));
    await screen.getByRole("button", "Cancel", {exact:true}).tap();
  }
  expect(results, "Control, outside while recording, and outside while transcribing all retain dictated text").toEqual([
    expect.stringContaining("double check this paragraph"),
    expect.stringContaining("double check this paragraph"),
    expect.stringContaining("double check this paragraph"),
  ]);
});
