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

test("Active real model download stays below 100 during its final disk write", WEB, async ({t3, app, browser, screen}) => {
  await t3.project("demo");
  await t3.open("/settings/voice");
  await screen.getByRole("combobox", "Transcribe with").tap();
  await screen.getByRole("option").nth(1).tap();
  await screen.getByPlaceholder("Search models").fill("Moonshine Tiny");
  await screen.getByRole("button", "Download", {exact:true}).tap();
  // Wait for real server byte counts, never substitute a status response.
  await browser.evaluate(async () => {
    for (;;) {
      const {models} = await (await fetch('/api/voice/models')).json();
      const model = models.find((m: {name:string}) => m.name === 'Moonshine Tiny');
      if (model?.state === 'downloading' && model.downloaded === model.size) return;
      await new Promise(resolve => setTimeout(resolve,100));
    }
  });
  await screen.getByText(/^(99|100)% downloaded$/).waitFor();
  await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 2000)));
  await app.screenshot("final-write-pending");
  await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 8000)));
  const value = await browser.evaluate(() => {
    const bar = document.querySelector('[role="progressbar"][aria-label="Moonshine Tiny download progress"]');
    return Number(bar?.getAttribute('aria-valuenow'));
  });
  expect(value, "An active download must remain below 100").toBeLessThan(100);
  await expect(screen.getByText(/^\d+% downloaded$/)).toHaveText("99% downloaded");
});
