import * as fs from "node:fs/promises";
import * as net from "node:net";
import { CommandId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { run } from "./shell.ts";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

// Scratch proof: a real setup terminal holds the checkout until cancellation or release.
test("Blocking setup refuses side chats and cancellation preserves a shared checkout", WEB,
async ({ t3, app, browser, screen }) => {
  let gate = Promise.withResolvers<string>();
  let verified = Promise.withResolvers<void>();
  const sockets = new Set<net.Socket>();
  const server = net.createServer(socket => {
    sockets.add(socket);
    socket.once("data", data => {
      if (data.toString().startsWith("VERIFIED")) verified.resolve();
      else gate.resolve(data.toString().trim());
    });
  });
  await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
  const address = server.address() as net.AddressInfo;
  const controlProject = await t3.project("verification");
  const other = await t3.thread({project: controlProject, title: "Shared checkout edits", messages: ["Start"]});
  const rpc = <A, E>(fn: (client: Effect.Success<ReturnType<typeof rpcClient>>) => Effect.Effect<A, E>) => runPromise(Effect.scoped(Effect.gen(function*() {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    return yield* fn(client);
  })));
  try {
    await rpc(c => c["server.updateSettings"]({patch: {defaultProjectScripts: [{id: "gate", name: "Blocking setup", command: "node gate.cjs", icon: "play", runOnWorktreeCreate: true, async: false}]}}));
    const outcomes = [];
    for (const mode of ["root", "nested"] as const) {
    const observer = await t3.thread({project: controlProject, title: `Cancellation verification ${mode}`, messages: ["Start"]});
    gate = Promise.withResolvers<string>();
    verified = Promise.withResolvers<void>();
    const project = await t3.project(`checkout-safety-${mode}`, {"gate.cjs": `const s = require('node:net').connect(${address.port}, '127.0.0.1'); s.on('connect', () => { console.log('CHECKOUT ALLOCATED\\nBLOCKING SETUP RUNNING\\nAgent waits for setup\\nWaiting for manual release'); s.write(process.cwd() + '\\n'); }); s.resume();`});
    if (mode === "nested") {
      await fs.mkdir(`${project}/nested`);
      await fs.writeFile(`${project}/nested/README.md`, "A separate repository inside the task folder.\n");
      const git = (args: string[]) => runPromise(run("git", args, {cwd: `${project}/nested`}));
      await git(["init", "--quiet", "--initial-branch=main"]);
      await git(["add", "."]);
      await git(["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--quiet", "-m", "Nested repository"]);
    }
    const {cli} = makeState(T3_HOME);
    const started = JSON.parse((await runPromise(cli(["thread", "start", project, "Wait for setup", "--title", `Parent setup ${mode}`, "--worktree", "main", "--branch", "checkout-safety-proof", "--provider", "devReplay", "--model", "multi-turn", "--json"]))).stdout);
    const allocated = await gate.promise;
    const checkout = mode === "nested" ? `${allocated}/nested` : allocated;
    if (mode === "nested" && !(await fs.stat(`${checkout}/.git`)).isFile()) throw new Error("The nested repository was not allocated as a worktree in the task folder");
    await t3.open(started);
    await screen.getByRole("button", "Cancel", {exact: true}).waitFor({timeout: 60000});
    const editor = browser.locator('[data-testid="composer-editor"]');
    await editor.fill("/side Inspect this checkout");
    await editor.press("Enter");
    // Both outcomes are observable real-app responses to the same command.
    await browser.locator('[data-side-chat-pane], [role="alert"]').first().waitFor({timeout: 30000});
    const sideOpened = await browser.locator('[data-side-chat-pane]').count() > 0;
    await app.screenshot(`${mode}-side-chat-during-blocking-setup`);

    // An independent client can already be bound to this allocated checkout.
    await rpc(c => c["orchestration.dispatchCommand"]({type: "thread.metadata.update", commandId: CommandId.make(crypto.randomUUID()), threadId: ThreadId.make(other.threadId), worktreePath: checkout}));
    await fs.writeFile(`${checkout}/shared-edit.txt`, "Disposable edits belonging to another thread.\n");
    await t3.open(started);
    await screen.getByRole("button", "Cancel", {exact: true}).tap();
    await screen.getByRole("button", "Cancel", {exact: true}).waitFor({state: "hidden"});
    await fs.writeFile(`${controlProject}/verify.cjs`, `const fs = require('node:fs'); const net = require('node:net'); const exists = fs.existsSync(${JSON.stringify(checkout + '/shared-edit.txt')}); console.log(${JSON.stringify("Checking " )} + ${JSON.stringify(mode)} + " checkout"); console.log(exists ? 'CHECKOUT PRESERVED' : 'CHECKOUT AND SHARED EDIT LOST'); if (exists) process.stdout.write(fs.readFileSync(${JSON.stringify(checkout + '/shared-edit.txt')}, 'utf8')); const s = net.connect(${address.port}, '127.0.0.1', () => s.end('VERIFIED'));`);
    await t3.open(observer);
    const input = browser.locator('[aria-label="Terminal input"][data-workspace-focus-default]');
    await screen.getByRole("button", "Toggle terminal drawer").tap();
    await input.waitFor({timeout: 30000});
    await input.focus();
    await browser.keyboard.type("PS1='> '; clear; node verify.cjs");
    await browser.keyboard.press("Enter");
    await verified.promise;
    const preserved = await fs.readFile(`${checkout}/shared-edit.txt`, "utf8").then(text => text === "Disposable edits belonging to another thread.\n", () => false);
    // Wait for the terminal's real command output before capturing.
    await browser.evaluate(() => new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))));
    await app.screenshot(`${mode}-shared-edit-after-cancellation`);
    outcomes.push({mode, sideChatRefused: !sideOpened, sharedEditSurvives: preserved});
    }
    expect(outcomes).toEqual([
      {mode: "root", sideChatRefused: true, sharedEditSurvives: true},
      {mode: "nested", sideChatRefused: true, sharedEditSurvives: true},
    ]);
  } finally {
    for (const socket of sockets) socket.destroy();
    server.close();
  }
});
