import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
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("Restored worktree recovers work published to a separate push remote", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo", { "README.md": "Recovery demonstration\n" });
  const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
  for (const name of ["origin", "publish"]) {
    await git("init", "--bare", "--quiet", "--initial-branch=main", `${project}/../${name}.git`);
    await git("remote", "add", name, `${project}/../${name}.git`);
  }
  await git("push", "-u", "origin", "main");
  await git("remote", "set-head", "origin", "main");
  await git("config", "remote.pushDefault", "publish");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client.subscribeServerConfig({}).pipe(Stream.filter(event => {
      const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
      return providers.some(p => p.instanceId === "devReplay" && p.models.some(m => m.slug === "multi-turn"));
    }), Stream.runHead);
  }).pipe(Effect.scoped));
  const { cli } = makeState(T3_HOME);
  const started = await runPromise(cli(["thread", "start", project, "Start", "--title", "Start", "--worktree", "main", "--branch", "t3/start", "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json"]));
  const thread = JSON.parse(started.stdout) as { threadId: string };
  const projection = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    return (yield* client["orchestration.getThreadProjection"](thread)).thread;
  }).pipe(Effect.scoped));
  const worktree = projection.worktreePath!;
  const branch = (await runPromise(run("git", ["branch", "--show-current"], { cwd: worktree }))).stdout.trim();
  await runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.writeFileString(`${worktree}/published.txt`, "Published work recovered successfully.\n")));
  const wtGit = (...args: string[]) => runPromise(run("git", args, { cwd: worktree }));
  await wtGit("add", "published.txt");
  await wtGit("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Publish work from the thread");
  const published = (await wtGit("rev-parse", "HEAD")).stdout.trim();
  await t3.open(thread);
  const details = screen.getByRole("button", "Toggle thread details panel", { exact: true });
  if ((await details.getAttribute("aria-pressed")) !== "true") await details.tap();
  await browser.locator('[role="group"][aria-label="Git actions for demo"]').hover();
  await screen.getByRole("button", "Git action options").tap();
  await screen.getByRole("menuitem", "Push", { exact: true }).tap();
  await screen.getByText(/^Pushed to /).waitFor({ timeout: 60000 });
  const tracking = (await git("rev-parse", `refs/remotes/publish/${branch}`)).stdout.trim();
  if (tracking !== published) throw new Error("Push did not publish the thread commit");
  await git("worktree", "remove", worktree);
  await git("branch", "-D", branch);
  await screen.getByRole("textbox").fill("Continue here");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("Continue here", { exact: true }).first().waitFor();
  await screen.getByText("second fixture turn complete", { exact: true }).waitFor({ timeout: 60000 });
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  const terminalText = async () => {
    await browser.evaluate(() => { document.body.dataset.terminalCopy = ""; window.addEventListener("copy", event => { document.body.dataset.terminalCopy = event.clipboardData?.getData("text/plain") ?? ""; }, { once: true }); return null; });
    await terminal.focus();
    await browser.keyboard.press("Control+Shift+A");
    await browser.keyboard.press("Control+Shift+C");
    return browser.evaluate(() => document.body.dataset.terminalCopy ?? "");
  };
  await expect.poll(terminalText).toContain("demo$");
  await browser.keyboard.type("clear; printf 'RESTORED THREAD WORKTREE\\n'; git log -1 --format=%s; printf '\\nPublished file:\\n'; cat published.txt; printf '\\nRemote published commit:\\n'; git log -1 --format=%s publish/" + branch + "; printf '\\nInspection complete\\n'\n");
  await expect.poll(terminalText).toMatch(/\nInspection complete\r?\n/);
  await browser.keyboard.press("ArrowRight");
  await app.screenshot("restored-published-work");
  expect((await wtGit("rev-parse", "HEAD")).stdout.trim()).toBe(published);
  expect(await runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.readFileString(`${worktree}/published.txt`)))).toBe("Published work recovered successfully.\n");
});
