/// <reference lib="dom" />
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { CommandId, ThreadId, ORCHESTRATION_PROTOCOL_VERSION } from "@t3tools/contracts";
import { expect } from "e2e";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
const T3_HOME = process.argv[2]!;
import { run } from "./shell.ts";
import { makeState, rpcClient, runPromise } from "./t3.ts";
const t3 = makeState(T3_HOME, { T3CODE_PORT: "13990" }).state;


  const project = await t3.project("task-boundary-proof", {
    ".gitignore": "outside/\nservices/\nC:/\n",
    "t3.json": '{"defaultThreadEnvMode":"worktree","ignoreRepositories":["outside","services","C:"]}',
  });
  const sibling = `${project}\\outside`;
  const child = `${project}/outside`;
  const literal = `${project}/services/api\\worker`;
  const drive = `${project}/C:/api`;
  for (const folder of [sibling, child, literal, drive]) {
    await mkdir(folder, { recursive: true });
    await writeFile(`${folder}/README.md`, "Repository fixture\n");
    const git = (...args: string[]) => runPromise(run("git", args, { cwd: folder }));
    await git("init", "--quiet", "--initial-branch=main");
    await git("add", ".");
    await git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--quiet", "-m", "Initial commit");
  }
  const cli = makeState(T3_HOME, { T3CODE_PORT: "13990" }).cli;
  const issued = await runPromise(cli(["auth", "session", "issue", "--token-only"]));
  const { origin } = JSON.parse(await readFile(`${T3_HOME}/userdata/server-runtime.json`, "utf8"));
  const headers = { authorization: `Bearer ${issued.stdout.trim()}`, "content-type": "application/json", "x-t3-orchestration-protocol": String(ORCHESTRATION_PROTOCOL_VERSION) };
  const snapshot = await (await fetch(`${origin}/api/projects`, { headers })).json();
  const id = snapshot.projects.find((p: { workspaceRoot: string }) => p.workspaceRoot === project).id;
  const result = await fetch(`${origin}/api/projects/mutate`, { method: "POST", headers, body: JSON.stringify({ type: "project.update", commandId: randomUUID(), projectId: id, trackedFolders: [
    { path: sibling, name: "task\\outside" },
    { path: child, name: "outside" },
  ] }) });
  if (!result.ok) throw new Error(`Project setup: ${await result.text()}`);

  const dispatch = async (threadId: string, worktreePath: string | null) => runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, origin);
    yield* client["orchestration.dispatchCommand"]({ type: "thread.metadata.update", commandId: CommandId.make(randomUUID()), threadId: ThreadId.make(threadId), worktreePath });
  }).pipe(Effect.scoped));
  const started = await runPromise(cli(["thread", "start", project, "Start", "--title", "Task folder boundary", "--provider", "devReplay", "--model", "multi-turn", "--worktree", "main", "--branch", "path-boundary-proof", "--wait", "--json"]));
  const thread = JSON.parse(started.stdout);
  const projection = await (await fetch(`${origin}/api/orchestration/threads/${thread.threadId}`, { headers })).json();
  const worktreePath = projection.projection.thread.worktreePath;
  const { taskFolder } = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, origin);
    return yield* client["workspace.taskFolder"]({ worktreePath });
  }).pipe(Effect.scoped));
  if (!taskFolder) throw new Error("Expected a multi-repository task folder");
  const historicalSibling = `${taskFolder.root}\\outside`;
  await mkdir(historicalSibling, { recursive: true });
  await writeFile(`${historicalSibling}/README.md`, "Initial content\n");
  const git = (...args: string[]) => runPromise(run("git", args, { cwd: historicalSibling }));
  await git("init", "--quiet", "--initial-branch=main");
  await git("add", ".");
  await git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--quiet", "-m", "Initial commit");
  // Record a real repository checkpoint while this thread uses the project folder, then move it into the task folder.
  const moved = await fetch(`${origin}/api/projects/mutate`, { method: "POST", headers, body: JSON.stringify({ type: "project.update", commandId: randomUUID(), projectId: id, workspaceRoot: taskFolder.root, trackedFolders: [{ path: historicalSibling, name: "external-sibling" }] }) });
  if (!moved.ok) throw new Error(`Project relocation: ${await moved.text()}`);
  await writeFile(`${taskFolder.root}/t3.json`, '{"defaultThreadEnvMode":"local"}');
  const historical = await t3.thread({ project: taskFolder.root, title: "Historical repository boundary", model: "question", messages: ["Record baseline"] });
  await writeFile(`${historicalSibling}/README.md`, "Changed while the agent waits for an answer\n");
  const ready = Promise.withResolvers<void>();
  const captured = runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, origin);
    return yield* client["orchestration.subscribeThread"]({ threadId: ThreadId.make(historical.threadId) }).pipe(
      Stream.tap(item => Effect.sync(() => { if (item.kind === "snapshot") ready.resolve(); })),
      Stream.filter(item => item.kind === "event" && item.event.type === "checkpoint-scope.created" && item.event.payload.cwd === historicalSibling),
      Stream.runHead,
    );
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  await ready.promise;
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, origin);
    yield* client["orchestration.dispatchCommand"]({ type: "thread.stop", commandId: CommandId.make(randomUUID()), threadId: ThreadId.make(historical.threadId) });
  }).pipe(Effect.scoped));
  await captured;
  await dispatch(historical.threadId, worktreePath);
  console.log(JSON.stringify({ threadId: historical.threadId, scopeNames: ["external-sibling"] }));
