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

test("Short-lived PowerShell invocations identify their actual program", WEB, async ({ t3, app, browser, screen }) => {
  const commands = [
    'pwsh -w Hidden -c "npm test"',
    'pwsh -NoProf -NonI -ExecutionPol Bypass -wd . -Comm "npm test"',
    'pwsh -Version 7 -c "git status"',
  ];
  const project = await t3.project("demo", { "package.json": '{"scripts":{"test":"echo tests passed"}}' });
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.opencode = { driver: "opencode", enabled: true, config: { binaryPath: "opencode" } };
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  // Preserve real incoming frames, briefly pausing delivery after each running command.
  // This makes an invocation that exits immediately inspectable without changing any event.
  await browser.addInitScript((targets) => {
    const Native = window.WebSocket;
    let index = 0;
    let frozen = false;
    let replaying = false;
    const pending: Array<{ socket: WebSocket; data: string }> = [];
    const parse = (data: string) => { try { return JSON.parse(data); } catch { return null; } };
    const matches = (value: unknown): boolean => {
      if (!value || typeof value !== "object") return false;
      const node = value as Record<string, unknown>;
      if (node.type === "command_execution" && node.status === "running" && node.input === targets[index]) return true;
      return Object.values(node).some(matches);
    };
    window.WebSocket = class extends Native {
      constructor(url: string | URL, protocols?: string | string[]) {
        super(url, protocols);
        if (!String(url).includes("orchestrationProtocol")) return;
        this.addEventListener("message", (event) => {
          if (replaying || typeof event.data !== "string") return;
          if (frozen) {
            event.stopImmediatePropagation();
            pending.push({ socket: this, data: event.data });
          } else if (matches(parse(event.data))) {
            frozen = true;
            index++;
            document.documentElement.dataset.powerShellFrame = String(index);
          }
        });
      }
    };
    (window as any).releasePowerShellFrame = () => {
      frozen = false;
      while (pending.length && !frozen) {
        const { socket, data } = pending.shift()!;
        if (matches(parse(data))) {
          frozen = true;
          index++;
          document.documentElement.dataset.powerShellFrame = String(index);
        }
        replaying = true;
        socket.dispatchEvent(new MessageEvent("message", { data }));
        replaying = false;
      }
    };
  }, commands);
  const { cli } = makeState(T3_HOME);
  let threadId: string | undefined;
  for (let attempt = 0; attempt < 8 && !threadId; attempt++) {
    const result = await runPromise(cli(["thread", "start", project,
      `First run sleep 15 with the bash tool, to let the browser open. Then run each command below exactly as written with the bash tool, one call per command, sequentially. Do not inspect files or run anything else. Continue after failures. Then reply exactly COMMANDS_COMPLETE.\n${commands.join("\n")}`,
      "--title", "PowerShell program labels", "--provider", "opencode", "--model", "anthropic/claude-haiku-5-5", "--json"], [0, 1]));
    if (result.stdout.includes("threadId")) threadId = JSON.parse(result.stdout).threadId;
  }
  if (!threadId) throw new Error("OpenCode did not start");
  await t3.open({ threadId });
  const observed: string[] = [];
  for (const [index, label] of ["window-style", "parameter-prefixes", "pwsh-version"].entries()) {
    await browser.locator(`html[data-power-shell-frame="${index + 1}"]`).waitFor({ state: "attached", timeout: 90_000 });
    const live = screen.getByRole("button", [
      /^Running (?:Hidden|npm)$/,
      /^Running (?:Bypass|npm)$/,
      /^Running (?:git|command)$/,
    ][index]);
    await live.waitFor({ timeout: 90_000 });
    if (index === 0) await live.tap();
    await screen.getByText(/Syncing messages/).waitFor({ state: "hidden" });
    observed.push((await live.textContent()) ?? "");
    await app.screenshot(label);
    await browser.evaluate(() => (window as any).releasePowerShellFrame());
  }
  await screen.getByText("COMMANDS_COMPLETE", { exact: true }).waitFor({ timeout: 90_000 });
  await expect(observed).toEqual(["Running npm", "Running npm", "Running command"]);
});
