import * as fs from "node:fs/promises";
import { T3_HOME } from "../e2e.config.ts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Push confirmation keeps later edits uncommitted", WEB, async ({ t3, app, screen, browser }) => {
  await fs.writeFile(`${T3_HOME}/bin/proof-shell`, "#!/bin/sh\nexport PS1='$ '\nexec /bin/bash --noprofile --norc -i\n", { mode: 0o755 });
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.opencode = { driver: "opencode", enabled: true, config: { binaryPath: "/usr/local/bin/opencode" } };
  settings.textGenerationModelSelection = { instanceId: "opencode", model: "anthropic/claude-haiku-5-5" };
  settings.sourceControlWriterModelSelection = { instanceId: "opencode", model: "anthropic/claude-haiku-5-5" };
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  const project = await t3.project("push-confirmation", { "README.md": "Initial content\n" });
  const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
  const write = (text: string) => runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.writeFileString(`${project}/README.md`, text)));
  await git("config", "user.name", "Scenario");
  await git("config", "user.email", "scenario@example.invalid");
  await git("clone", "--bare", ".", "../origin.git");
  await git("remote", "add", "origin", "../origin.git");
  await git("fetch", "origin");
  await git("branch", "--set-upstream-to=origin/main", "main");
  const initial = (await git("rev-parse", "HEAD")).stdout.trim();
  await write("Initial content\nLocal commit\n");
  await git("add", "README.md");
  await git("commit", "-m", "local commit");
  const local = (await git("rev-parse", "HEAD")).stdout.trim();
  const thread = await t3.thread({ project, title: "Push existing commits", messages: ["first"] });
  await t3.open(thread);
  await screen.getByRole("button", "Push", { exact: true }).tap();
  await screen.getByText("Push to default ref?", { exact: true }).waitFor();
  await browser.evaluate(() => {
    for (const animation of document.getAnimations()) {
      if (Number.isFinite(animation.effect?.getComputedTiming().endTime)) animation.finish();
    }
  });
  await app.screenshot("push-confirmation");
  await write("Initial content\nLocal commit\nunreviewed change\n");
  await screen.getByRole("button", "Push to main", { exact: true }).tap();
  await screen.getByText("Push to default ref?", { exact: true }).waitFor({ state: "hidden" });
  // The remote ref marks completion of the real push on both commits.
  await expect.poll(async () => (await git("--git-dir=../origin.git", "rev-parse", "main")).stdout.trim(), { timeout: 180_000 }).not.toBe(initial);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = screen.getByRole("textbox", "Terminal input");
  await input.waitFor();
  await expect(input).toHaveAttribute("data-workspace-focus-default", "");
  await input.focus();
  await browser.keyboard.type("PS1='$ '; clear; printf 'WORKING TREE AFTER PUSH\\n'; git status --short; printf '\\nLOCAL COMMITS\\n'; git log -3 --format='%h %s'; printf '\\nREMOTE COMMITS\\n'; git --git-dir=../origin.git log -3 --format='%h %s'; touch .git/proof-done\n");
  await expect.poll(() => runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.exists(`${project}/.git/proof-done`)))).toBe(true);
  await app.screenshot("after-push");
  const outcome = {
    head: (await git("rev-parse", "HEAD")).stdout.trim(),
    remote: (await git("--git-dir=../origin.git", "rev-parse", "main")).stdout.trim(),
    status: (await git("status", "--porcelain")).stdout.trim(),
  };
  expect(outcome).toEqual({ head: local, remote: local, status: "M README.md" });
});
