/// <reference lib="dom" />
import { watch } from "node:fs";
import { mkdir, rename, writeFile, readFile } from "node:fs/promises";
import { CommandId, EnvironmentHttpApi } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { FetchHttpClient } from "effect/http";
import * as HttpApiClient from "effect/http-api/HttpApiClient";
import { T3_HOME } from "../e2e.config.ts";
import { expect } from "e2e";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("New worktree preserves a base branch ending in U+00A0", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("plainproj");
  await rename(`${project}/.git`, `${project}/../seed.git`);
  const repo = `${project}/repo`;
  await mkdir(repo);
  const git = (...args: string[]) => runPromise(run("git", args, { cwd: repo }));
  await git("init", "--initial-branch=main");
  const commit = async (value: string) => {
    await writeFile(`${repo}/which.txt`, value);
    await git("add", ".");
    await git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", value);
  };
  await commit("main");
  await git("switch", "-c", "release");
  await commit("release");
  await git("switch", "-c", "release\u00a0");
  await commit("nbsp");
  const wanted = (await git("rev-parse", "HEAD")).stdout.trim();
  await git("switch", "main");
  await runPromise(Effect.gen(function* () {
    const { stdout } = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
    const headers = { authorization: `Bearer ${stdout.trim()}` };
    const client = yield* HttpApiClient.make(EnvironmentHttpApi, { baseUrl: app.baseUrl });
    const { projects } = yield* client.projects.snapshot({ headers });
    const entry = projects.find((p) => p.workspaceRoot === project)!;
    yield* client.projects.mutate({ headers, payload: { type: "project.update", commandId: CommandId.make(`track-${entry.id}`), projectId: entry.id, trackFolders: [{ path: repo, name: "repo" }] } });
  }).pipe(Effect.provide(FetchHttpClient.layer)));
  const thread = await t3.thread({ project, title: "Setup", messages: ["Start"], model: "showcase" });
  await t3.open(thread);
  await screen.getByRole("button", "New thread in plainproj", { exact: true }).waitFor({ timeout: 180000 });
  await screen.getByRole("button", "New thread in plainproj", { exact: true }).tap();
  await screen.getByRole("combobox", "Workspace", { exact: true }).tap();
  await screen.getByRole("option", "New worktree", { exact: true }).tap();
  await screen.getByRole("button", /^Repositories in the new worktree/).tap();
  const branch = screen.getByRole("textbox", "Base branch", { exact: true });
  await branch.fill("  release\u00a0  ");
  const actual = await browser.evaluate(() => (document.querySelector('input[aria-label="Base branch"]') as HTMLInputElement).value);
  await app.screenshot("base-branch-input");
  await browser.keyboard.press("Escape");
  const composer = screen.getByRole("textbox");
  await composer.fill("go");
  await composer.press("Enter");
  await screen.getByText("This turn is a replay.", { exact: false }).waitFor({ timeout: 60000 });
  const trees = (await git("worktree", "list", "--porcelain")).stdout;
  const created = trees.split("\n\n").find((block) => block.includes("refs/heads/t3/"));
  const path = created!.split("\n")[0]!.slice("worktree ".length);
  const root = path.slice(0, -"/repo".length);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = browser.locator('[aria-label="Terminal input"][data-workspace-focus-default]');
  await input.waitFor();
  const ready = new Promise<void>((resolve) => {
    const watcher = watch(root, (_, name) => { if (name === "proof-ready") { watcher.close(); resolve(); } });
  });
  await input.focus();
  await browser.keyboard.type("export PS1='$ '; clear; printf 'Selected base commit: '; git -C repo log -1 --format='%h %s'; printf 'which.txt: '; cat repo/which.txt; printf '\\n'; touch proof-ready\n");
  await ready;
  await app.screenshot("created-worktree");
  expect(actual).toBe("release\u00a0");
  expect(created?.includes(`HEAD ${wanted}`)).toBe(true);
  expect(await readFile(`${path}/which.txt`, "utf8")).toBe("nbsp");
});
