/// <reference lib="dom" />
import { randomUUID } from "node:crypto";
import * as Effect from "effect/Effect";
import { CommandId, ThreadId } from "@t3tools/contracts";
import { readFile } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB, makeState, rpcClient, runPromise, environmentId } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";

// Feed identical recorded speech into a real MediaStream; ASR and draft insertion remain real.
test("An approval keeps ongoing dictation and its transcript", WEB, async ({ t3, app, browser, screen }) => {
  const fixture = process.env.DICTATION_FIXTURE_DIR!;
  const state = makeState(T3_HOME);
  const runtime = JSON.parse(await readFile(`${T3_HOME}/userdata/server-runtime.json`, "utf8"));
  const issued = await runPromise(state.cli(["auth", "session", "issue", "--token-only"]));
  const post = async (path: string, body?: unknown) => {
    const response = await fetch(`${runtime.origin}${path}`, {
      method: "POST", headers: { authorization: `Bearer ${issued.stdout.trim()}`, "content-type": "application/json" },
      ...(body ? { body: JSON.stringify(body) } : {}),
    });
    if (!response.ok) throw new Error(`${path}: ${response.status} ${await response.text()}`);
    return response.text();
  };
  await post("/api/voice/models/link", { path: `${fixture}/moonshine-tiny-Q8_0.gguf` });
  await post("/api/voice/models/select", { modelId: "handy-computer/moonshine-tiny-gguf" });
  await post("/api/voice/models/prepare");
  const project = await t3.project("Dictation demo");
  const thread = await t3.thread({ project, title: "Approval during dictation", model: "approval", messages: ["Write the requested file"] });
  const envId = await runPromise(environmentId(app.baseUrl!));
  const audio = (await readFile(`${fixture}/jfk.wav`)).toString("base64");
  await browser.addInitScript(({ audio, envId }) => {
    localStorage.setItem("t3code:voice-audio-grant:v1", JSON.stringify({ id: "dictation-evidence", destination: { kind: "environment", environmentId: envId } }));
    navigator.mediaDevices.getUserMedia = async () => {
      const context = new AudioContext();
      await context.resume();
      const bytes = Uint8Array.from(atob(audio), (c) => c.charCodeAt(0));
      const source = context.createBufferSource();
      source.buffer = await context.decodeAudioData(bytes.buffer);
      const destination = context.createMediaStreamDestination();
      source.connect(destination);
      (window as any).speechFinished = new Promise<void>((resolve) => { source.onended = () => resolve(); });
      source.start();
      return destination.stream;
    };
  }, { audio, envId });
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, runtime.origin);
    yield* client["orchestration.dispatchCommand"]({ type: "thread.runtime-mode.set", commandId: CommandId.make(randomUUID()), threadId: ThreadId.make(thread.threadId), runtimeMode: "approval-required" });
  }).pipe(Effect.scoped));
  await t3.open(thread);
  await screen.getByRole("button", "Start voice input", { exact: true }).tap();
  await browser.locator('button[aria-label="Finish voice input"]').waitFor({ state: "visible" });
  await app.screenshot("recording-before-approval");
  await runPromise(state.cli(["thread", "send", thread.threadId, "Write the file again"]));
  await browser.locator('button').filter({ hasText: /^Approve$/ }).waitFor({ state: "visible" });
  await app.screenshot("approval-arrives-during-dictation");
  await browser.evaluate(async () => { await (window as any).speechFinished; return null; });
  // On base this control has disappeared because approval cancelled the recording.
  await browser.evaluate(() => { (document.querySelector('button[aria-label="Finish voice input"]') as HTMLButtonElement | null)?.click(); return null; });
  try {
    await expect(screen.getByRole("textbox")).toContainText(/country/i);
  } finally {
    await app.screenshot("dictation-finished-with-approval-pending");
  }
});
