/// <reference lib="dom" />
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Unlinking a voice model clears its cancelled download and preserves other files", WEB, async ({t3, app, browser, screen}) => {
  await browser.emulateMedia({colorScheme:"dark"});
  const project = await t3.project("voice-proof");
  const thread = await t3.thread({project,title:"Voice model removal",messages:["hello"],model:"default"});
  const dir = path.join(T3_HOME,"userdata/speech/models");
  const name = "whisper-small.en-Q8_0.gguf";
  const external = "/tmp/factory-pr-46715-evidence-1/whisper-small.en-Q8_0.gguf";
  await t3.open("/settings/voice");
  await screen.getByRole("combobox","Transcribe with").tap();
  await screen.getByRole("option").nth(1).tap();
  const card = browser.locator('div[class*="@container/model"]').filter({has:screen.getByText("Whisper Small English",{exact:true})});
  // Schedule cancellation from the real UI, as in the triage reproduction.
  await browser.evaluate(() => {
    const observer = new MutationObserver(() => {
      const cancel = document.querySelector<HTMLButtonElement>('button[aria-label="Cancel Whisper Small English download"]');
      if (cancel) { observer.disconnect(); setTimeout(() => cancel.click(),250); }
    });
    observer.observe(document.body,{childList:true,subtree:true});
  });
  await card.getByRole("button","Download",{exact:true}).tap();
  await screen.getByRole("button","Cancel Whisper Small English download").waitFor({state:"hidden"});
  const partial = path.join(dir,name+".part");
  // A real retained download is a precondition, not the verdict.
  const retained = await fs.stat(partial);
  if (retained.size === 0 || retained.size >= 269674144) throw new Error("Cancellation did not retain a partial download");
  await fs.writeFile(path.join(dir,"unrelated.gguf.part"),"unrelated retained download");
  await screen.getByRole("textbox","Path to a model file or folder already on this environment").fill(external);
  await screen.getByRole("button","Use existing",{exact:true}).tap();
  const unlink = screen.getByRole("button","Stop using your Whisper Small English file; the file stays on disk");
  await unlink.waitFor();
  await unlink.tap();
  await unlink.waitFor({state:"hidden"});
  const files = await fs.readdir(dir);
  const result = {
    partialRemoved:!files.includes(name+".part"),
    linkRemoved:!files.includes(name),
    sidecarsRemoved:!files.includes(name+".verified") && !files.includes(name+".source"),
    externalPreserved:(await fs.stat(external)).size===269674144,
    unrelatedPreserved:(await fs.readFile(path.join(dir,"unrelated.gguf.part"),"utf8"))==="unrelated retained download"
  };
  const report = ["VOICE MODEL REMOVAL — REAL FILESYSTEM",`Cancelled download retained ${retained.size} bytes before unlink.`,"",...Object.entries(result).map(([key,value])=>`${key}: ${value}`),"","Model directory after unlink:",...files.sort()].join("\n");
  await fs.writeFile(path.join(project,"result.txt"),report);
  await fs.writeFile(path.join(project,"show-result.sh"),"#!/bin/sh\nprintf '\\033[2J\\033[H'\ncat result.txt\nprintf '\\n'\n");
  await t3.open(thread);
  await screen.getByRole("button","Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  // Retry shell input only until the shell has actually started.
  for(let attempt=0;attempt<10;attempt++) {
    await terminal.focus();
    await browser.keyboard.type("export PS1=''; sh show-result.sh; echo ready > shell-ready");
    await browser.keyboard.press("Enter");
    try { await fs.readFile(path.join(project,"shell-ready")); break; } catch {}
    await new Promise(resolve=>setTimeout(resolve,500));
  }
  await app.screenshot("voice-model-files-after-unlink");
  expect(result).toEqual({partialRemoved:true,linkRemoved:true,sidecarsRemoved:true,externalPreserved:true,unrelatedPreserved:true});
});
