import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { readFile, writeFile, mkdir, chmod } from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { randomUUID } from "node:crypto";
import { CommandId, ProjectId, ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const scratch = "/tmp/factory-issue-40350-evidence-3";
const git = (cwd: string, ...args: string[]) => execFileSync("/usr/bin/git", args, { cwd, encoding: "utf8" }).trim();

test("A review guide finishes using the tracked repository checkout", WEB, async ({ t3, app, screen, browser }) => {
  const sha = git(APP_DIR, "rev-parse", "HEAD");
  const run = `${scratch}/${sha.slice(0,10)}-${Date.now()}`;
  await mkdir(run, { recursive: true });
  const root = await t3.project("Hello-World");
  git(root, "remote", "add", "origin", "https://github.com/octocat/Hello-World.git");
  git(root, "fetch", "--quiet", "origin", "master");
  git(root, "reset", "--hard", "FETCH_HEAD");
  const tracked = `${run}/Spoon-Knife`;
  git(run, "clone", "--quiet", "https://github.com/octocat/Spoon-Knife.git", tracked);
  const { cli } = makeState(T3_HOME);
  const token = (await runPromise(cli(["auth", "session", "issue", "--token-only"]))).stdout.trim();
  const origin = app.baseUrl ?? "";
  const snapshot = await (await fetch(`${origin}/api/projects`, { headers: { authorization: `Bearer ${token}` } })).json();
  const project = snapshot.projects.find((p: { workspaceRoot: string }) => p.workspaceRoot === root);
  if (!project) throw new Error("Seeded project missing");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, origin);
    yield* client["projects.mutate"]({ type: "project.update", commandId: CommandId.make(randomUUID()), projectId: ProjectId.make(project.id), trackedFolders: [{ path: tracked, name: "Spoon-Knife" }] });
    yield* client["server.updateSettings"]({ patch: { reviewGuidesEnabled: true, reviewGuideModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-6-luna" } }, providerInstanceMutation: { operation: "upsert", instanceId: ProviderInstanceId.make("codex"), instance: { driver: ProviderDriverKind.make("codex"), enabled: true, config: { binaryPath: "/usr/local/bin/codex", setupMode: "existing" } } } });
  }).pipe(Effect.scoped));
  // Record the real git worktree command without publishing environment paths.
  await writeFile(`${T3_HOME}/bin/git`, `#!/bin/sh\ncase " $* " in\n  *" worktree add "*) for last; do :; done; printf 'checkoutHead: source checkout=%s; command=git worktree add; commit=%s\\n' "$(basename "$PWD")" "$last" >> '${run}/checkout.txt' ;;\nesac\nexec /usr/bin/git "$@"\n`);
  await chmod(`${T3_HOME}/bin/git`, 0o755);
  await t3.open(`/pull-requests?repository=octocat/Spoon-Knife&number=42362&selectedProjectId=${project.id}&selectedHost=github.com`);
  await screen.getByRole("button", "Guide", { exact: true }).tap();
  await screen.getByRole("button", "Write guide", { exact: true }).tap();
  const reference = { projectId: ProjectId.make(project.id), repository: "octocat/Spoon-Knife", number: 42362, host: "github.com" };
  const readGuide = () => runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, origin);
    return yield* client["pullRequests.reviewGuide"](reference);
  }).pipe(Effect.scoped));
  let terminal = await readGuide();
  await expect.poll(async () => {
    terminal = await readGuide();
    const rejected = await browser.evaluate(() => document.body.innerText.includes("Could not start a review guide"));
    return rejected || terminal.run?._tag === "Failed" || (terminal.guide !== null && terminal.run === null);
  }, { timeout: 200_000, interval: 1_000 }).toBe(true);
  const uiSucceeded = terminal.guide !== null && terminal.run === null;
  await writeFile(`${run}/guide-result.json`, JSON.stringify({ commit: sha, repository: "octocat/Spoon-Knife", result: terminal }, null, 2));
  if (uiSucceeded) {
    const first = terminal.guide!.stops[0]!;
    await expect(screen.getByRole("heading", first.title, { exact: true })).toBeVisible();
    await expect(screen.getByText("Loading code...", { exact: true })).toBeHidden();
    const path = first.files[0]?.path ?? first.excerpts[0]?.path;
    if (path) await expect(screen.getByText(path, { exact: true }).first()).toBeVisible();
  }
  await app.screenshot("tracked-repository-guide-result");

  const instanceId = ProviderInstanceId.make("mcp-proof");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, origin);
    yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: { operation: "upsert", instanceId, instance: { driver: ProviderDriverKind.make("acpRegistry"), displayName: "MCP proof driver", enabled: true, config: { source: "local", commandPath: process.execPath, commandArgs: [`${scratch}/mcp-agent.mjs`, `${run}/mcp-result.json`, `${run}/checkout.txt`] } } } });
  }).pipe(Effect.scoped));
  const started = await runPromise(cli(["thread", "start", root, "Write a guide for the tracked Spoon-Knife pull request.", "--title", "Tracked repository MCP guide", "--provider", instanceId, "--model", "default", "--wait", "--json"]));
  const thread = JSON.parse(started.stdout);
  await t3.open(thread);
  await expect(screen.getByText("Called write_pull_request_guides", { exact: false })).toBeVisible();
  await expect(screen.getByText("Git process audit:", { exact: false })).toBeVisible();
  await app.screenshot("mcp-tracked-repository-result");
  const mcp = JSON.parse(await readFile(`${run}/mcp-result.json`, "utf8"));
  const mcpData = mcp.structuredContent ?? mcp;
  const mcpAccepted = mcpData.guides?.[0]?.outcome === "started" || mcpData.guides?.[0]?.outcome === "running";
  if (mcpAccepted) {
    await expect.poll(async () => { terminal = await readGuide(); return terminal.run === null || terminal.run?._tag === "Failed"; }, { timeout: 200_000, interval: 1_000 }).toBe(true);
    await t3.open(`/pull-requests?repository=octocat/Spoon-Knife&number=42362&selectedProjectId=${project.id}&selectedHost=github.com`);
    await screen.getByRole("button", "Guide", { exact: true }).tap();
    await expect(screen.getByText("Reading the change...", { exact: true })).toBeHidden();
    await expect(screen.getByRole("heading", terminal.guide!.stops[0]!.title, { exact: true })).toBeVisible();
    await expect(screen.getByText("Loading code...", { exact: true })).toBeHidden();
    await app.screenshot("mcp-guide-finished");
  }
  await writeFile(`${run}/final-result.json`, JSON.stringify({ commit: sha, uiSucceeded, mcpAccepted, result: terminal }, null, 2));
  expect(uiSucceeded).toBe(true);
  expect(mcpAccepted).toBe(true);
  expect(terminal.guide !== null && terminal.run === null).toBe(true);
  expect(await readFile(`${run}/checkout.txt`, "utf8")).toContain("source checkout=Spoon-Knife");
});
