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

test("Restore banner identifies the nested separate checkout", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("nested-repository-demo", { ".gitignore": "DerivedData.noindex/\n" });
  const nested = `${project}/DerivedData.noindex/site`;
  await mkdir(nested, { recursive: true });
  const git = (cwd: string, ...args: string[]) => runPromise(run("git", args, { cwd }));
  await git(nested, "init", "--initial-branch=main");
  await git(nested, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--allow-empty", "-m", "Initial nested repository");
  const cli = (args: string[], allowExit = [0]) => runPromise(makeState(T3_HOME).cli(args, allowExit));
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client["server.updateSettings"]({ patch: { worktreesDirectory: "/tmp/factory-pr-45800-a1796026352-evidence-1/worktrees" } });
    yield* client.subscribeServerConfig({}).pipe(Stream.filter((event) => {
      const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
      return providers.some((provider) => provider.instanceId === "devReplay" && provider.models?.some((model) => model.slug === "multi-turn"));
    }), Stream.runHead);
  }).pipe(Effect.scoped, Effect.timeout("60 seconds")));
  const started = await cli(["thread", "start", project, "Hello", "--title", "Restore nested task folder", "--worktree", "main", "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json"]);
  const thread = JSON.parse(started.stdout);
  const state = JSON.parse((await cli(["thread", "show", thread.threadId, "--json"])).stdout);
  const root = state.thread.worktreePath;
  if (!root) throw new Error("Thread has no worktree");
  const blocked = `${root}/DerivedData.noindex/site`;
  await git(nested, "worktree", "remove", "--force", blocked);
  await git(project, "clone", nested, blocked);
  await browser.setViewport({ width: 1280, height: 900 });
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Continue after checkout replacement");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText(/(?:Failed to recreate|holds a separate checkout|Could not recreate)/).first().waitFor({ timeout: 60_000 });
  await app.screenshot("blocked-nested-checkout");
  await expect(screen.getByRole("alert")).toContainText("The DerivedData.noindex/site folder holds a separate checkout instead of the thread's worktree. Move it away and try again.");
  await rename(blocked, `${root}-moved-separate-checkout`);
  await screen.getByRole("textbox").fill("Continue after moving the separate checkout away");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("second fixture turn complete", { exact: false }).waitFor({ timeout: 60_000 });
  await git(blocked, "rev-parse", "--git-common-dir");
  await screen.getByText("Continue after moving the separate checkout away", { exact: true }).waitFor();
  await app.screenshot("restored-after-moving-checkout");
});
