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

test('Installed voice model transcribes while another real model downloads', {...WEB, timeout: 2_700_000}, async ({t3, app, browser, screen}) => {
  const audio = (await readFile(process.env.PROOF_AUDIO!)).toString('base64');
  await browser.addInitScript((base64) => {
    let play: (() => Promise<void>) | undefined;
    Object.defineProperty(navigator.mediaDevices, 'getUserMedia', {value: async () => {
      const context = new AudioContext();
      await context.resume();
      const bytes = Uint8Array.from(atob(base64), 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);
      play = () => new Promise<void>(resolve => {
        source.onended = () => resolve();
        source.start();
      });
      return destination.stream;
    }});
    Object.assign(window, {playProofSpeech: () => play?.() ?? Promise.resolve()});
  }, audio);
  const project = await t3.project('Voice proof');
  const thread = await t3.thread({project, title:'Voice proof', messages:[]});
  await t3.open(thread);
  await t3.open('/settings/voice');
  await screen.getByRole('combobox', 'Transcribe with').tap();
  await screen.getByRole('option').nth(1).tap();
  const search = screen.getByRole('searchbox', 'Search transcription models');
  await search.fill('Parakeet Unified');
  await screen.getByRole('button', 'Download', {exact:true}).tap();
  await screen.getByRole('button', 'Test model', {exact:true}).waitFor({timeout:1_200_000});
  await search.fill('Nemotron Streaming');
  await screen.getByRole('button', 'Download', {exact:true}).tap();
  await search.fill('');
  await screen.getByRole('progressbar', 'Nemotron Streaming 3.5 download progress').waitFor();
  await screen.getByRole('button', 'Test model', {exact:true}).tap();
  // Preparation either rejects with the reported error, or opens the actual recorder.
  await browser.evaluate(async () => {
    await new Promise<void>(resolve => {
      const ready = () => !!document.querySelector('[aria-label="Dismiss voice input error"]') || !!document.querySelector('[aria-label="Finish voice input"]:not(:disabled)');
      if (ready()) return resolve();
      const observer = new MutationObserver(() => {if (ready()) {observer.disconnect(); resolve();}});
      observer.observe(document.body, {subtree:true, childList:true, attributes:true});
    });
    return null;
  });
  const failed = await browser.evaluate(() => !!document.querySelector('[aria-label="Dismiss voice input error"]'));
  if (!failed) {
    await browser.evaluate(async () => {await (window as any).playProofSpeech(); return null;});
    await screen.getByRole('button', 'Finish voice input', {exact:true}).tap();
    await screen.getByRole('status', 'Test transcript').waitFor({timeout:60000});
  }
  if (!failed) await screen.getByRole('button', 'Test model', {exact:true}).waitFor({timeout:60000});
  const during = await browser.evaluate(() => ({
    text: document.querySelector('[aria-label="Test transcript"]')?.textContent ?? '',
    downloading: !!document.querySelector('[role="progressbar"][aria-label="Nemotron Streaming 3.5 download progress"]'),
    error: !!document.querySelector('[aria-label="Dismiss voice input error"]'),
  }));
  await app.screenshot('installed-model-during-other-download');
  if (failed) {
    await screen.getByRole('button', 'Record again', {exact:true}).tap();
    await screen.getByRole('button', 'Record again', {exact:true}).waitFor();
    await app.screenshot('record-again-during-other-download');
  }
  await screen.getByRole('button', 'Cancel Nemotron Streaming 3.5 download', {exact:true}).waitFor({state:'hidden', timeout:1_200_000});
  if (failed) await screen.getByRole('button', 'Dismiss voice input error', {exact:true}).tap();
  await screen.getByRole('button', 'Test model', {exact:true}).tap();
  await browser.evaluate(async () => {
    await new Promise<void>(resolve => {
      const ready = () => !!document.querySelector('[aria-label="Dismiss voice input error"]') || !!document.querySelector('[aria-label="Finish voice input"]:not(:disabled)');
      if (ready()) return resolve();
      const observer = new MutationObserver(() => {if (ready()) {observer.disconnect(); resolve();}});
      observer.observe(document.body, {subtree:true, childList:true, attributes:true});
    });
    await (window as any).playProofSpeech();
    return null;
  });
  await screen.getByRole('button', 'Finish voice input', {exact:true}).tap();
  await screen.getByRole('button', 'Test model', {exact:true}).waitFor({timeout:60000});
  await app.screenshot('installed-model-after-download-control');
  const control = await browser.evaluate(() => document.querySelector('[aria-label="Test transcript"]')?.textContent ?? '');
  expect(control, 'The installed model works after download completes').toMatch(/country/i);
  expect(during, 'A real transcript is produced while Nemotron is still downloading').toMatchObject({error:false, downloading:true});
  expect(during.text).toMatch(/country/i);
});
