/// <reference lib="dom" />
import { writeFileSync } from 'node:fs';
import { expect } from 'e2e';
import * as Effect from 'effect/Effect';
import { T3_HOME } from '../e2e.config.ts';
import { rpcClient, runPromise, test, WEB } from './t3.ts';
const ID = 'handy-computer/moonshine-tiny-gguf';
const setPhase = (phase: number) => writeFileSync(`${process.env.VOICE_PROOF_DIR}/phase`, String(phase));
test('Voice download reports completion only after the last byte', WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project('voice-demo');
  const thread = await t3.thread({ project, title: 'Voice notes', messages: ['Ready for voice notes.'] });
  await runPromise(Effect.gen(function*() {
    const rpc = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* rpc['server.updateSettings']({patch:{speechModelId: ID}});
  }).pipe(Effect.scoped));
  await t3.open('/settings/voice');
  await screen.getByRole('combobox', 'Transcribe with').tap();
  await screen.getByRole('option').nth(1).tap();
  const values: Array<{surface:string, incomplete:number|null, complete:number|null}> = [];
  const snapshot = async (label:string) => {
    await browser.evaluate(async () => { await new Promise(r=>setTimeout(r,600)); return null; });
    await app.screenshot(label);
  };
  const waitBytes = async (wanted:number) => {
    await browser.evaluate(async ({wanted, id}) => {
      const deadline = Date.now()+180000;
      while(Date.now()<deadline) {
        const response = await fetch('/api/voice/models');
        const data = await response.json();
        if(data.models.find((m:any)=>m.id===id)?.downloaded===wanted) { await new Promise(r=>setTimeout(r,1500)); return null; }
        await new Promise(r=>setTimeout(r,250));
      }
      throw new Error('The real transfer did not reach '+wanted+' bytes');
    }, {wanted, id:ID});
  };
  const readValue = () => browser.evaluate(() => {
    const bar = Array.from(document.querySelectorAll('[role="progressbar"]')).find(e=>e.getAttribute('aria-label')?.includes('download progress'));
    return bar ? Number(bar.getAttribute('aria-valuenow')) : null;
  });
  for (const surface of ['settings', 'setup']) {
    setPhase(0);
    if(surface==='settings') {
      await screen.getByRole('searchbox', 'Search transcription models').fill('Moonshine Tiny');
      await screen.getByText('Moonshine Tiny',{exact:true}).first().waitFor();
      await browser.evaluate(() => {
        const name = Array.from(document.querySelectorAll('span')).find(e=>e.textContent==='Moonshine Tiny');
        const card = name?.closest('[class*="@container/model"]');
        card?.scrollIntoView({block:'center'});
        const button = Array.from(card?.querySelectorAll('button')??[]).find(e=>e.textContent?.trim()==='Download');
        if(!button) throw new Error('Moonshine Tiny Download button missing');
        button.click();
        return null;
      });
    } else {
      await browser.evaluate(async (id) => {
        await fetch('/api/voice/models/remove',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({modelId:id})});
        return null;
      }, ID);
      await runPromise(Effect.gen(function*() {
        const rpc = yield* rpcClient(T3_HOME, app.baseUrl!);
        yield* rpc['server.updateSettings']({patch:{speechModelId:ID}});
      }).pipe(Effect.scoped));
      await t3.open(thread);
      await screen.getByRole('button','Start voice input').tap();
      await screen.getByRole('button','Download model',{exact:true}).tap();
    }
    await waitBytes(35378244);
    await snapshot(surface+'-incomplete-9975');
    const incomplete = await readValue();
    setPhase(1);
    await waitBytes(35466912);
    await snapshot(surface+'-all-bytes-100');
    const complete = await readValue();
    setPhase(2);
    await screen.getByText(surface==='settings'?'Verifying download…':'Verifying…',{exact:true}).waitFor();
    await snapshot(surface+'-verifying');
    setPhase(3);
    await screen.getByText(surface==='settings'?'Selected':'Voice input is ready',{exact:true}).first().waitFor();
    await snapshot(surface+'-complete');
    values.push({surface,incomplete,complete});
  }
  expect(values,'Incomplete downloads stay below 100; all bytes received can report 100').toEqual([
    {surface:'settings',incomplete:99,complete:100},
    {surface:'setup',incomplete:99,complete:100},
  ]);
});
