import { DEFAULT_TERMINAL_ID } from "@t3tools/contracts";
import * as Stream from "effect/Stream";
import { dirname } from "node:path";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { mkdir, writeFile, rm } from "node:fs/promises";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("A running task folder protects its repository until the turn ends", WEB, async ({ t3, app, browser, screen }) => {
  // Capture-only presentation: expose the real error detail and remove its local path.
  await browser.addInitScript(() => {
    new MutationObserver(() => {
      for (const node of document.querySelectorAll('[data-slot="toast-description"]')) {
        for (const child of node.childNodes) {
          if (child.nodeType === Node.TEXT_NODE && child.textContent?.includes(' (/')) {
            child.textContent = child.textContent.replace(/ \(\/[^)]*\)/g, ' (local checkout)');
          }
        }
      }
    }).observe(document, { childList: true, subtree: true, characterData: true });
    document.addEventListener('DOMContentLoaded', () => {
      const style = document.createElement('style');
      style.textContent = '[data-slot="toast-description"] { -webkit-line-clamp: unset !important; }';
      document.head.append(style);
    });
  });
  const warm = await t3.project("warmup");
  await t3.thread({ project: warm, title: "Ready", messages: ["Start"] });
  const project = await t3.project("shop");
  await rm(`${project}/.git`, { recursive: true });
  const api = `${project}/api`;
  await mkdir(api);
  await writeFile(`${api}/index.ts`, "export const value = 1;\n");
  const gitAt = (cwd: string, ...args: string[]) => runPromise(run("git", args, { cwd }));
  await gitAt(api, "init", "--initial-branch=main");
  await gitAt(api, "config", "user.name", "Scenario");
  await gitAt(api, "config", "user.email", "scenario@example.invalid");
  await gitAt(api, "add", ".");
  await gitAt(api, "commit", "-m", "Initial commit");
  await gitAt(api, "branch", "review");
  const started = await runPromise(makeState(T3_HOME).cli(["thread", "start", project, "Edit index.ts in api and keep working", "--title", "Edit API index", "--worktree", "main", "--provider", "devReplay", "--model", "bench-stream", "--json"]));
  const thread = JSON.parse(started.stdout);
  await t3.open(thread);
  const stop = screen.getByRole("button", "Stop generation");
  await stop.waitFor();
  const trees = (await gitAt(api, "worktree", "list", "--porcelain")).stdout;
  const checkout = trees.split("\n").filter(line => line.startsWith("worktree ")).map(line => line.slice(9)).find(path => path !== api);
  if (!checkout) throw Error("No nested API worktree was created");
  const git = (...args: string[]) => gitAt(checkout, ...args);
  const original = (await git("branch", "--show-current")).stdout.trim();
  await writeFile(`${checkout}/index.ts`, "export const value = 1;\nexport const edited = true;\n");
  const details = screen.getByRole("button", "Toggle thread details panel", { exact: true });
  if ((await details.getAttribute("aria-pressed")) !== "true") await details.tap();
  const row = screen.getByRole("group", "Repository api", { exact: true });
  await row.waitFor();
  const commit = async (message: string) => {
    await row.waitFor();
    const header = row.getByRole("button", /^api /);
    if (await header.getAttribute("aria-expanded") !== "true") await header.tap();
    await row.getByRole("button", "Git action options").tap();
    await screen.getByRole("menuitem", "Commit", { exact: true }).tap();
    await screen.getByPlaceholder("Leave empty to auto-generate").fill(message);
    await screen.getByRole("button", "Commit on new branch", { exact: true }).tap();
    await screen.getByRole("dialog", "Commit changes", { exact: true }).waitFor({ state: "hidden" });
    await row.getByText(message, { exact: true }).or(screen.getByText("Action failed", { exact: true })).waitFor();
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().filter(a => a.effect?.getTiming().iterations !== Infinity).map(a => a.finished.catch(() => {})));
    });
  };
  await commit("Export the edited value");
  const refused = await screen.getByText("Action failed", { exact: true }).isVisible();
  if (refused) await screen.getByText(/'Edit API index' is still working in this checkout/).waitFor();
  await app.screenshot("running-task-folder-after-branch-commit");
  const busyBranch = (await git("branch", "--show-current")).stdout.trim();
  // Exercise two other guarded operations through the same real server used by the UI.
  const guarded = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    const summarize = { onFailure: (e: { detail?: string; message?: string }) => ({ status: "refused", detail: e.detail ?? e.message ?? String(e) }), onSuccess: () => ({ status: "switched", detail: "Checkout changed while the turn was active" }) };
    const switched = yield* client["vcs.switchRef"]({ cwd: checkout, refName: "review" }).pipe(Effect.match(summarize));
    const created = yield* client["vcs.createRef"]({ cwd: checkout, refName: "manual-feature", switchRef: true }).pipe(Effect.match(summarize));
    return [switched, created];
  }).pipe(Effect.scoped));
  const report = guarded.map((r, i) => `${["vcs.switchRef(review)", "vcs.createRef(manual-feature, switchRef=true)"][i]}: ${r.status}\n${r.detail}`).join("\n\n") + `\n\nBranch: ${(await git("branch", "--show-current")).stdout.trim()}\nEND OF LIVE SERVER RESULTS\n`;
  await writeFile(`${dirname(checkout)}/guard-results.txt`, report);
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    const input = { threadId: thread.threadId, terminalId: DEFAULT_TERMINAL_ID };
    yield* client["terminal.open"]({ ...input, cwd: dirname(checkout), env: { T3CODE_TERMINAL_SHELL: "/bin/sh", PS1: "$ " } });
    yield* client["terminal.write"]({ ...input, data: "cat guard-results.txt\r" });
    yield* client["terminal.attach"]({ ...input }).pipe(
      Stream.map(e => e.type === "snapshot" ? e.snapshot.history : e.type === "output" ? e.data : ""),
      Stream.scan(() => "", (all, chunk) => all + chunk),
      Stream.filter(text => text.includes("END OF LIVE SERVER RESULTS")),
      Stream.runHead,
    );
  }).pipe(Effect.scoped, Effect.timeout("20 seconds")));
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  await screen.getByLabel("Terminal input").waitFor();
  // The terminal input mounts before its canvas has painted the server history.
  await browser.evaluate(async () => {
    await new Promise<void>(resolve => {
      const painted = () => {
        const canvas = document.querySelector('[aria-label="Terminal input"]')?.parentElement?.querySelector('canvas');
        const context = canvas?.getContext('2d');
        if (canvas && context) {
          const pixels = context.getImageData(0, 0, Math.min(900, canvas.width), Math.min(200, canvas.height)).data;
          let ink = 0;
          for (let i = 0; i < pixels.length; i += 4) if (pixels[i + 3] > 0 && pixels[i] + pixels[i + 1] + pixels[i + 2] < 500) ink++;
          if (ink > 500) { resolve(); return; }
        }
        requestAnimationFrame(painted);
      };
      painted();
    });
  });
  await app.screenshot("running-task-folder-other-guarded-switches");
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  // Capture recovery on both commits before making the differential assertion.
  await stop.tap();
  await stop.waitFor({ state: "hidden" });
  const close = screen.getByRole("button", "Dismiss notification", { exact: true });
  if (await close.isVisible()) await close.tap();
  // Reload clears the prior error toast before waiting for the new success.
  await t3.open(thread);
  await writeFile(`${checkout}/index.ts`, "export const value = 1;\nexport const edited = true;\nexport const finished = true;\n");
  await commit("Export the finished value");
  await app.screenshot("finished-task-folder-after-branch-commit");
  expect((await git("branch", "--show-current")).stdout.trim()).not.toBe(original);
  expect(busyBranch).toBe(original);
  expect(guarded.map(r => r.status)).toEqual(["refused", "refused"]);
});
