import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { mkdirSync, writeFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { execFileSync } from "node:child_process";
import { test, WEB, runPromise, makeState } from "./t3.ts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import * as Auth from "../../apps/server/src/auth/EnvironmentAuth.ts";
import * as Config from "../../apps/server/src/config.ts";
import { mcpToolSession } from "../../apps/server/src/mcp/AcpMcpStdioBridge.ts";
import { readLiveServerRuntimeState } from "../../apps/server/src/serverRuntimeState.ts";

// The fixture and all tool responses are rebuilt for each side; no database rows are copied.
test("Dangling origin HEAD refuses deleted bases before creating a thread", WEB, async ({ t3, app, screen, browser }) => {
  const output = join("/tmp/factory-issue-36261-evidence-5", `run-${Date.now()}`);
  const seed = join(output, "seed");
  mkdirSync(seed, { recursive: true });
  const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
  git(seed, "init", "--initial-branch=development");
  writeFileSync(join(seed, "README.md"), "Synthetic stale-default reproduction\n");
  git(seed, "add", ".");
  git(seed, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Initial commit");
  const remote = join(dirname(seed), "origin.git");
  git(seed, "clone", "--bare", seed, remote);
  const clone = join(dirname(seed), "Stale-default");
  git(seed, "clone", remote, clone);
  git(seed, "branch", "main");
  git(seed, "push", remote, "main");
  git(remote, "symbolic-ref", "HEAD", "refs/heads/main");
  git(remote, "update-ref", "-d", "refs/heads/development");
  git(clone, "fetch", "--prune");
  await runPromise(makeState(T3_HOME).cli(["project", "add", clone, "--title", "Stale default reproduction"]));
  const root = await t3.thread({ project: clone, title: "Stale default reproduction", messages: ["fixture"] });
  await t3.open(root);
  await screen.getByRole("button", "New thread", { exact: true }).tap();
  await browser.evaluate(() => document.fonts.ready.then(() => true));
  await screen.getByRole("combobox", "Workspace").tap();
  await screen.getByRole("option", "New worktree", { exact: true }).tap();
  // Capture the same new-thread screen on both revisions, before any launch.
  await app.screenshot("new-thread-default");
  const transcript: unknown[] = [{ step: "git fixture", symbolicHead: git(clone, "symbolic-ref", "refs/remotes/origin/HEAD"), advertisedDefault: git(clone, "ls-remote", "--symref", "origin", "HEAD"), refs: git(clone, "show-ref") }];
  const responses = await runPromise(Effect.gen(function* () {
    const config = yield* Config.ServerConfig;
    const runtime = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath);
    if (Option.isNone(runtime)) throw new Error("Scenario server not running");
    const auth = yield* Auth.EnvironmentAuth;
    const issued = yield* Effect.acquireRelease(auth.issueMcpClientSession({ label: "Scenario proof", access: "full-access", peerLink: false, client: { deviceType: "bot" } }), (s) => auth.revokeSession(s.sessionId));
    const session = yield* mcpToolSession({ endpoint: `${runtime.value.origin}/mcp`, authorization: `Bearer ${issued.token}`, clientName: "scenario-proof" });
    const call = (name: string, args: Record<string, unknown>) => session.call(name, args).pipe(Effect.tap((result) => Effect.sync(() => transcript.push({ name, args, result }))));
    const list: any = yield* call("t3_project_list", {});
    const projectId = list.structuredContent.projects.find((p: any) => p.workspaceRoot === clone).id;
    const results: any[] = [];
    for (const baseRef of ["origin/development", "origin/HEAD", "origin/main"]) {
      const result: any = yield* call("t3_thread_launch", { projectId, title: `Worktree from ${baseRef}`, message: "fixture", modelSelection: { instanceId: "devReplay", model: "multi-turn" }, workspaceStrategy: { type: "worktree", baseRef, startFromOrigin: true, branch: `proof-${baseRef.split("/").at(-1)?.toLowerCase()}` } });
      results.push(result);
      if (!result.isError && result.structuredContent?.threadId) {
        yield* call("t3_thread_wait", { threadId: result.structuredContent.threadId, timeoutMs: 120000 });
        yield* call("t3_thread_read", { threadId: result.structuredContent.threadId });
      }
    }
    return results;
  }).pipe(Effect.scoped, Effect.provide(Auth.layerRuntime.pipe(Layer.provideMerge(Config.layerTest(APP_DIR, T3_HOME)), Layer.provide(NodeCrypto.layer)))));
  // Redact environment-local paths from the public transcript.
  writeFileSync(join(output, "mcp-transcript.json"), JSON.stringify(transcript, null, 2).replaceAll(dirname(seed), "<fixture>").replaceAll(T3_HOME, "<scenario-home>").replaceAll(APP_DIR, "<app>"));
  console.log(`TRANSCRIPT ${output}/mcp-transcript.json`);
  const valid = responses[2].structuredContent;
  if (valid?.threadId) {
    await t3.open({ threadId: valid.threadId });
    await expect(screen.getByText("first fixture turn complete", { exact: false })).toBeVisible({ timeout: 60000 });
    await expect(screen.getByText("Syncing messages...", { exact: false })).not.toBeVisible({ timeout: 60000 });
    await app.screenshot("explicit-real-default-worktree");
  }
  for (const [index, label] of ["deleted-branch-failure", "origin-HEAD-failure"].entries()) {
    const accepted = responses[index].structuredContent;
    if (accepted?.threadId) {
      await t3.open({ threadId: accepted.threadId });
      await expect(screen.getByText("ref_not_found", { exact: false }).first()).toBeVisible();
      await expect(screen.getByText("Syncing messages...", { exact: false })).not.toBeVisible({ timeout: 60000 });
      if (await browser.evaluate(() => Boolean(document.querySelector('[aria-label="Dismiss notification"]')))) {
        await screen.getByRole("button", "Dismiss notification").first().tap();
      }
      await app.screenshot(label);
    }
  }
  // Both stale bases must be refused up front; accepting and then failing is the reported bug.
  expect(responses[0].isError === true && responses[1].isError === true).toBe(true);
  expect(JSON.stringify(responses.slice(0, 2)).includes("No thread was created")).toBe(true);
  expect(JSON.stringify(responses.slice(0, 2)).includes("project has no usable remote")).toBe(false);
});
