import * as fs from "node:fs/promises";
import * as path from "node:path";
import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, environmentId, runPromise, test, WEB } from "./t3.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import * as Effect from "effect/Effect";
import { CommandId, ThreadId, ProviderInstanceId } from "@t3tools/contracts";

test(
  "Background Details adds information instead of repeating the waiting line",
  WEB,
  async ({ t3, app, browser, screen }) => {
    await browser.emulateMedia({ colorScheme: "light", reducedMotion: "reduce" });
    const capture = async (label: string) => {
      await browser.evaluate(async () => {
        await Promise.all(
          document
            .getAnimations()
            .filter(
              (a) =>
                a.effect &&
                a.effect.getTiming().iterations !== Infinity &&
                a.playState !== "finished",
            )
            .map((a) => a.finished.catch(() => {})),
        );
      });
      const box = await browser.evaluate((dialog: boolean) => {
        const nodes = dialog
          ? [...document.querySelectorAll("[data-slot=dialog-popup]")]
          : [...document.querySelectorAll("[data-thread-now-line]")];
        if (!nodes.length) return null;
        const rs = nodes.map((n) => n.getBoundingClientRect());
        const x = Math.min(...rs.map((r) => r.x)),
          y = Math.min(...rs.map((r) => r.y));
        return {
          x: Math.floor(x),
          y: Math.floor(y),
          width: Math.ceil(Math.max(...rs.map((r) => r.right)) - x),
          height: Math.ceil(Math.max(...rs.map((r) => r.bottom)) - y),
        };
      }, label.includes("dialog"));
      const pixels = async (file: string) =>
        box
          ? execFileSync(
              "convert",
              [file, "-crop", `${box.width}x${box.height}+${box.x}+${box.y}`, "+repage", "rgba:-"],
              { maxBuffer: 16 * 1024 * 1024 },
            )
          : fs.readFile(file);
      let previous = await app.screenshot(label + "-stability-start");
      for (let i = 0; i < 40; i++) {
        await new Promise((resolve) => setTimeout(resolve, 500));
        const next = await app.screenshot(label + "-stability-" + i);
        if ((await pixels(previous)).equals(await pixels(next))) {
          const file = await app.screenshot(label);
          const region =
            box ??
            (await browser.evaluate(() => {
              const nodes = [...document.querySelectorAll("[data-thread-now-line]")];
              if (!nodes.length) return null;
              const rs = nodes.map((n) => n.getBoundingClientRect());
              const x = Math.min(...rs.map((r) => r.x)),
                y = Math.min(...rs.map((r) => r.y));
              return {
                x: Math.floor(x),
                y: Math.floor(y),
                width: Math.ceil(Math.max(...rs.map((r) => r.right)) - x),
                height: Math.ceil(Math.max(...rs.map((r) => r.bottom)) - y),
              };
            }));
          await fs.writeFile(file + ".region.json", JSON.stringify(region));
          if (region)
            execFileSync("convert", [
              file,
              "-crop",
              `${region.width}x${region.height}+${region.x}+${region.y}`,
              "+repage",
              file,
            ]);
          return file;
        }
        previous = next;
      }
      throw new Error("Screen did not settle for " + label);
    };
    const settingsPath = path.join(T3_HOME, "userdata/settings.json");
    const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
    settings.providerInstances.opencode = { driver: "opencode", enabled: true, config: {} };
    await fs.writeFile(settingsPath, JSON.stringify(settings));
    const project = await t3.project("background-demo", {
      "output.sh":
        "#!/bin/sh\nwhile [ ! -f emit-output ]; do sleep 0.2; done\necho FIRST_OUTPUT\nsleep 600\n",
    });
    const { cli } = makeState(T3_HOME);
    let started = "";
    await expect
      .poll(
        async () => {
          const result = await runPromise(
            cli(
              [
                "thread",
                "start",
                project,
                "Run exactly `sleep 600 && echo done` with the shell tool as a background shell (background true). Do not add a description. Then register waiting for that shell using T3 background wait. Do not wait in a foreground tool. Say exactly WAITING before registering the wait.",
                "--title",
                "Background work",
                "--provider",
                "opencode",
                "--model",
                "anthropic/claude-haiku-5-5",
                "--json",
              ],
              [0, 1],
            ),
          ).catch(() => undefined);
          if (result?.stdout.includes("threadId")) started = result.stdout;
          return started.length > 0;
        },
        { timeout: 60000 },
      )
      .toBe(true);
    const { threadId } = JSON.parse(started);
    await t3.open({ threadId });
    const line = browser
      .locator("[data-thread-now-line]")
      .filter({ hasText: "sleep 600 && echo done" });
    await expect(line).toBeVisible({ timeout: 90000 });
    await capture("silent-full-line");
    const details = line.getByRole("button", "Details", { exact: true });
    const redundant = await details.isVisible();
    if (redundant) {
      await details.click();
      await capture("redundant-dialog");
      await screen.getByRole("button", "Close", { exact: true }).click();
    }
    await browser.setViewport({ width: 375, height: 800 });
    await capture("narrow-line");
    await details.click();
    await capture("narrow-full-command-dialog");
    await screen.getByRole("button", "Close", { exact: true }).click();
    await browser.setViewport({ width: 1280, height: 800 });
    await capture("restored-full-line");
    // A running command stays silent until the driver releases a real file gate.
    const outputStart = await runPromise(
      cli([
        "thread",
        "start",
        project,
        "Run exactly `sh output.sh` with the shell tool as a background shell (background true), then use t3_background_wait to register waiting for that shell. Do not add a description, run another command, or inspect files. End your turn after registering the wait.",
        "--title",
        "Output arrives",
        "--provider",
        "opencode",
        "--model",
        "anthropic/claude-haiku-5-5",
        "--json",
      ]),
    );
    const outputThread = JSON.parse(outputStart.stdout);
    await t3.open(outputThread);
    const outputLine = browser
      .locator("[data-thread-now-line]")
      .filter({ hasText: "sh output.sh" });
    await outputLine.waitFor({ timeout: 90000 });
    await capture("output-before-first-text");
    const outputDetails = outputLine.getByRole("button", "Details", { exact: true });
    const outputRepeats = await outputDetails.isVisible();
    await fs.writeFile(path.join(project, "emit-output"), "go");
    await outputDetails.waitFor({ timeout: 30000 });
    await capture("output-details-appeared");
    await outputDetails.click();
    await screen
      .getByRole("dialog")
      .getByText("FIRST_OUTPUT", { exact: false })
      .waitFor({ timeout: 30000 });
    await capture("output-dialog");
    await screen.getByRole("button", "Close", { exact: true }).click();

    const childStart = await runPromise(
      cli([
        "thread",
        "start",
        project,
        "Use the native subagent tool with background true to delegate to the general agent. Description: Subagent: Waiting helper. Prompt: Before doing anything, use the question tool to ask which color I prefer with red and blue options. After I answer, run sleep 600 with the shell tool in the foreground, then reply DONE. Once launched, end your own turn immediately without waiting.",
        "--title",
        "Child action",
        "--provider",
        "opencode",
        "--model",
        "anthropic/claude-haiku-5-5",
        "--json",
      ]),
    );
    const childThread = JSON.parse(childStart.stdout);
    await t3.open(childThread);
    const childLine = browser
      .locator("[data-thread-now-line]:not([role=alert])")
      .filter({ hasText: "Waiting helper" });
    await childLine.waitFor({ timeout: 90000 });
    await capture("subagent-line");
    await childLine.getByRole("button", "Details", { exact: true }).click();
    await screen.getByRole("button", "Open subagent", { exact: true }).waitFor({ timeout: 30000 });
    await capture("subagent-action-dialog");
    await screen.getByRole("button", "Open subagent", { exact: true }).click();

    const secondServer = startSecondServer(app.baseUrl ?? "");
    try {
      const { host } = await secondServer.ready;
      const target = await runPromise(environmentId(host));
      const remoteProject = await makeState(SECOND_HOME).state.project("remote-demo");
      const remoteProjectId = await runPromise(
        Effect.gen(function* () {
          const primary = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
          const second = yield* rpcClient(SECOND_HOME, host);
          for (const client of [primary, second])
            yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } });
          const pairing = yield* makeState(SECOND_HOME).cli([
            "auth",
            "pairing",
            "create",
            "--json",
          ]);
          yield* primary["peerLinks.link"]({
            url: host,
            alternateUrls: [],
            pairingCode: JSON.parse(pairing.stdout).credential,
            access: "full-access",
          });
          const { projects } = yield* second["orchestration.getArchivedShellSnapshot"]({});
          return projects.find((p) => p.workspaceRoot === remoteProject)!.id;
        }).pipe(Effect.scoped),
      );
      const remoteStart = await runPromise(
        cli([
          "thread",
          "start",
          project,
          `Call orchestrator_capabilities for environmentId ${target}. Then call delegate_task once with title Remote helper, mode async, task Ask which color I prefer with red and blue choices, and target ${JSON.stringify({ environmentId: target, projectId: remoteProjectId, providerInstanceId: "devReplay", model: "question" })}. End your own turn immediately after the task starts. Do not call task_status or wait.`,
          "--title",
          "Remote child action",
          "--provider",
          "opencode",
          "--model",
          "anthropic/claude-haiku-5-5",
          "--json",
        ]),
      );
      await t3.open(JSON.parse(remoteStart.stdout));
      const remoteLine = browser
        .locator("[data-thread-now-line]:not([role=alert])")
        .filter({ hasText: "Remote helper" });
      await remoteLine.waitFor({ timeout: 90000 });
      await capture("remote-subagent-line");
      await remoteLine.getByRole("button", "Details", { exact: true }).click();
      await screen
        .getByRole("button", "Open subagent", { exact: true })
        .waitFor({ timeout: 30000 });
      await capture("remote-subagent-action-dialog");
      await screen.getByRole("button", "Open subagent", { exact: true }).click();
    } finally {
      await secondServer.stop();
    }
    const attentionParent = await t3.thread({
      project,
      title: "Other Now line",
      messages: ["Start"],
      model: "multi-turn",
    });
    const attentionChild = ThreadId.make("scenario-side-question");
    await runPromise(
      Effect.flatMap(rpcClient(T3_HOME, app.baseUrl ?? ""), (client) =>
        client["orchestration.dispatchCommand"]({
          type: "thread.fork",
          commandId: CommandId.make("scenario:side-question:fork"),
          sourceThreadId: ThreadId.make(attentionParent.threadId),
          targetThreadId: attentionChild,
          sourcePoint: { type: "latest_stable" },
          sideChat: true,
          title: "Side question asks which color you prefer before beginning the next step",
          createdBy: "user",
          creationSource: "web",
        }),
      ).pipe(Effect.scoped),
    );
    await expect
      .poll(
        async () => {
          const result = await runPromise(
            cli(["thread", "show", attentionChild, "--json"], [0, 1]),
          ).catch(() => undefined);
          return result?.stdout.includes("Side question asks") ?? false;
        },
        { timeout: 30000 },
      )
      .toBe(true);
    await runPromise(
      Effect.flatMap(rpcClient(T3_HOME, app.baseUrl ?? ""), (client) =>
        client["orchestration.dispatchCommand"]({
          type: "thread.model-selection.set",
          commandId: CommandId.make("scenario:side-question:model"),
          threadId: attentionChild,
          modelSelection: { instanceId: ProviderInstanceId.make("devReplay"), model: "question" },
        }),
      ).pipe(Effect.scoped),
    );
    await runPromise(
      cli(["thread", "send", attentionChild, "Ask a question", "--wait", "--json"], [0, 2]),
    );
    await t3.open(attentionParent);
    await screen.getByRole("button", "Open question", { exact: true }).waitFor({ timeout: 30000 });
    await capture("other-now-line");
    await browser.setViewport({ width: 375, height: 800 });
    await capture("other-now-line-narrow");
    expect(redundant).toBe(false);
    expect(outputRepeats).toBe(false);
  },
);
