import { CommandId, EnvironmentHttpApi } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { FetchHttpClient } from "effect/http";
import * as HttpApiClient from "effect/http-api/HttpApiClient";
import { existsSync, writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Retry runs required setup after restoring a missing worktree", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("Setup retry");
  const cli = (args: string[], codes = [0]) => runPromise(makeState(T3_HOME).cli(args, codes));
  const first = JSON.parse((await cli(["thread", "start", project, "Start", "--title", "Restored workspace setup", "--worktree", "main", "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json"])).stdout);
  const thread = {threadId: first.threadId};
  const worktrees = execFileSync("git", ["-C", project, "worktree", "list", "--porcelain"], {encoding:"utf8"});
  const worktree = worktrees.split("\n").filter(line => line.startsWith("worktree ")).map(line => line.slice(9)).find(path => path !== project)!;
  await runPromise(Effect.gen(function* () {
    const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
    const headers = {authorization: `Bearer ${issued.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(crypto.randomUUID()), projectId:entry.id, scripts:[{id:"prepare",name:"Prepare",icon:"configure",command:'test -f "$T3CODE_PROJECT_ROOT/allow-setup" && touch setup-ready',runOnWorktreeCreate:true,async:false}]}});
  }).pipe(Effect.provide(FetchHttpClient.layer)));
  await t3.open(thread);
  execFileSync("git", ["-C", project, "worktree", "remove", "--force", worktree]);
  await cli(["thread", "send", thread.threadId, "Continue here", "--wait", "--json"], [0,1,2]);
  await screen.getByText("Couldn't set up restored workspace", {exact:false}).waitFor();
  await app.screenshot("restored-setup-failed");
  writeFileSync(`${project}/allow-setup`, "");
  await cli(["thread", "send", thread.threadId, "Try again", "--wait", "--json"], [0,1,2]);
  await screen.getByText("second fixture turn complete", {exact:false}).waitFor();
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByRole("textbox", "Terminal input");
  await terminal.waitFor();
  await expect.poll(async () => {
    await terminal.focus();
    await browser.keyboard.type("printf '\\nRequired synchronous setup after retry: '; if test -f setup-ready; then echo PASSED; else echo MISSING; fi; touch evidence-shown");
    await browser.keyboard.press("Enter");
    return existsSync(`${worktree}/evidence-shown`);
  }, {timeout:30000}).toBe(true);
  await app.screenshot("setup-after-retry");
  await expect(existsSync(`${worktree}/setup-ready`)).toBe(true);
});
