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

// Synthetic microphone only; transcription, dictionary correction and UI are real.
test("C sharp dictionary preserves unrelated letters in local dictation", WEB, async ({t3,app,screen,browser}) => {
  await t3.project("Voice demo");
  await t3.open();
  await screen.getByText("Voice demo").first().tap();
  await app.open("/settings/voice");
  await screen.getByRole("combobox", "Transcribe with").tap();
  await screen.getByRole("option", "Scenario", {exact:true}).tap();
  await browser.evaluate(async () => {
    const r = await fetch('/api/voice/models/download', {method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({modelId:'handy-computer/parakeet-unified-en-0.6b-gguf'})});
    if(!r.ok) throw new Error(await r.text());
  });
  await browser.reload();
  await screen.getByRole("searchbox", "Search transcription models").fill("Parakeet Unified English");
  await screen.getByRole("textbox", "Add a word or phrase to the dictionary").first().fill("C#");
  await screen.getByRole("textbox", "Add a word or phrase to the dictionary").first().press("Enter");
  await browser.evaluate(async (audio) => {
    const bytes = Uint8Array.from(atob(audio), c => c.charCodeAt(0));
    const context = new AudioContext();
    await context.resume();
    const buffer = await context.decodeAudioData(bytes.buffer);
    Object.defineProperty(navigator.mediaDevices, 'enumerateDevices', {value:async()=>[{kind:'audioinput',deviceId:'default',groupId:'synthetic',label:'Synthetic microphone',toJSON(){return this;}}]});
    let done: () => void;
    (window as any).audioDone=new Promise<void>(resolve => {done=resolve;});
    Object.defineProperty(navigator.mediaDevices, 'getUserMedia', {value:async()=>{
      const dest=context.createMediaStreamDestination();
      const source=context.createBufferSource(); source.buffer=buffer; source.connect(dest);
      source.onended=()=>done();
      (window as any).playAudio=()=>source.start();
      return dest.stream;
    }});
  }, readFileSync(process.env.VOICE_EVIDENCE_AUDIO!).toString('base64'));
  await screen.getByRole('button','Test model',{exact:true}).tap();
  await screen.getByRole('button','Finish voice input',{exact:true}).waitFor();
  await browser.evaluate(async()=> {(window as any).playAudio(); await (window as any).audioDone; return true;});
  await screen.getByRole('button','Finish voice input',{exact:true}).tap();
  await screen.getByRole('button','Test model',{exact:true}).waitFor();

  await app.screenshot('local-transcript');
  await expect(screen.getByRole('status','Test transcript')).not.toContainText('C#');
});
