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

test("Terminal soft reset refreshes cached Changes totals", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("parent");
  const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
  await git("config", "user.name", "Scenario");
  await git("config", "user.email", "scenario@example.invalid");
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const settingsPath = `${T3_HOME}/userdata/settings.json`;
    const settings = JSON.parse(yield* fs.readFileString(settingsPath));
    yield* fs.writeFileString(settingsPath, JSON.stringify({ ...settings, automaticGitFetchInterval: 0 }));
    yield* run("git", ["init", "--quiet", "--initial-branch=main", `${project}/../child`]);
    yield* fs.writeFileString(`${project}/../child/README.md`, "Submodule fixture\n");
    yield* run("git", ["add", "."], { cwd: `${project}/../child` });
    yield* run("git", ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-qm", "Initial"], { cwd: `${project}/../child` });
  }));
  await git("-c", "protocol.file.allow=always", "submodule", "add", "../child", "child");
  await git("commit", "-qm", "Add submodule");
  await runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.writeFileString(`${project}/notes.txt`, Array.from({ length: 40 }, (_, i) => `Note ${i + 1}\n`).join(""))));
  await git("add", "notes.txt");
  await git("commit", "-qm", "Add forty notes");
  // Let Git's cached index stat data settle before the clean status read.
  await runPromise(Effect.sleep("4 seconds"));
  await git("status", "--porcelain");
  const thread = await t3.thread({ project, title: "Soft reset refresh", messages: ["Start"] });
  await t3.open(thread);
  const changes = screen.getByRole("button", /^Changes\s+Uncommitted/);
  await changes.waitFor();
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = browser.locator('[aria-label="Terminal input"][data-workspace-focus-default]');
  await input.waitFor();
  await input.focus();
  await browser.keyboard.type("PS1='$ '; clear\n");
  await runPromise(Effect.sleep("3 seconds"));
  await app.screenshot("clean-before-reset");
  await input.focus();
  await browser.keyboard.type("git reset --soft HEAD~1; git status --short; git diff --cached --stat\n");
  // Observe the watcher without opening Changes or triggering a forced refresh.
  await runPromise(Effect.sleep("20 seconds"));
  await app.screenshot("changes-after-soft-reset");
  try {
    await expect(changes).toHaveText(/\+40\s*-0/);
  } finally {
    await app.screenshot("changes-final");
  }
});
