import { watch } from "node:fs";
import { mkdir, rename, writeFile, readFile, lstat } from "node:fs/promises";
import { dirname } from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("A failed worktree add keeps the nested repository and neighboring links accessible", WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("shop", { "tools/run.sh": "echo tools-ready\n", "api/README.md": "API project\n" });
    await rename(`${project}/.git`, `${dirname(project)}/unused-root-git`);
    const git = (cwd: string, ...args: string[]) => runPromise(run("git", args, { cwd }));
    await git(`${project}/api`, "init", "-b", "main");
    await git(`${project}/api`, "add", ".");
    await git(`${project}/api`, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Initial API");
    const started = await runPromise(makeState(T3_HOME).cli(["thread", "start", project, "Inspect the shop workspace", "--title", "Failed repository add", "--worktree", "main", "--branch", "feature", "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json"]));
    const thread = JSON.parse(started.stdout);
    const listed = await git(`${project}/api`, "worktree", "list", "--porcelain");
    const apiWorktree = listed.stdout.split("\n").filter(line => line.startsWith("worktree ")).map(line => line.slice(9)).find(path => path !== `${project}/api`)!;
    const folder = dirname(apiWorktree);
    await mkdir(`${project}/tools/new`);
    await git(`${project}/tools/new`, "init", "-b", "main");
    await writeFile(`${project}/tools/new/uncommitted.txt`, "new repository remains accessible\n");
    await browser.setViewport({ width: 1440, height: 1000 });
    await t3.open(thread);
    await screen.getByRole("button", "Toggle terminal drawer").tap();
    const input = screen.getByRole("textbox", "Terminal input");
    await browser.locator('[aria-label="Terminal input"][data-workspace-focus-default]').waitFor();
    await input.focus();
    const marker = (name: string) => {
      const ready = Promise.withResolvers<void>();
      const watcher = watch(folder, (_event, file) => {
        if (file === name) { watcher.close(); ready.resolve(); }
      });
      return ready.promise;
    };
    // A cursor-position reply confirms the browser terminal consumed the preceding output.
    const terminalReady = marker(".proof-terminal-ready");
    await browser.keyboard.type("PS1='$ '; clear; printf 'Ready to add the nested repository\\n'; printf '\\033[6n'; IFS= read -rs -d R -t 5 cursor; touch .proof-terminal-ready\n");
    await terminalReady;
    await app.screenshot("before-add");
    await screen.getByRole("button", "Other repositories...", { exact: true }).tap();
    await screen.getByRole("menuitem", "new", { exact: true }).tap();
    await screen.getByText("Could not add new", { exact: true }).waitFor();
    const outputReady = marker(".proof-output-ready");
    await input.focus();
    await browser.keyboard.type("clear; printf 'After failed worktree add\\n\\n'; for p in tools/run.sh tools/new/uncommitted.txt; do if test -f \"$p\"; then printf 'ACCESSIBLE  %s\\n' \"$p\"; else printf 'MISSING     %s\\n' \"$p\"; fi; done; printf '\\nNeighbor content: '; cat tools/run.sh; printf 'Repository content: '; if test -f tools/new/uncommitted.txt; then cat tools/new/uncommitted.txt; else printf 'unavailable\\n'; fi; printf '\\033[6n'; IFS= read -rs -d R -t 5 cursor; touch .proof-output-ready\n");
    await outputReady;
    await app.screenshot("after-failed-add");
    await expect.poll(async () => {
      try {
        return { repository: await readFile(`${folder}/tools/new/uncommitted.txt`, "utf8"), neighbor: await readFile(`${folder}/tools/run.sh`, "utf8"), neighborIsLink: (await lstat(`${folder}/tools/run.sh`)).isSymbolicLink() };
      } catch { return { repository: "MISSING", neighbor: await readFile(`${folder}/tools/run.sh`, "utf8"), neighborIsLink: (await lstat(`${folder}/tools/run.sh`)).isSymbolicLink() }; }
    }).toEqual({ repository: "new repository remains accessible\n", neighbor: "echo tools-ready\n", neighborIsLink: true });
  });
