/// <reference lib="dom" />
import { execFileSync } from "node:child_process";
import { mkdirSync, writeFileSync, symlinkSync, cpSync } from "node:fs";
import { randomUUID } from "node:crypto";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { ProjectId, CommandId } from "@t3tools/contracts";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB, rpcClient, runPromise } from "./t3.ts";

const git = process.env.REFTABLE_GIT!;

test("Imported reftable worktree retains its actual branch before any VCS subscription", WEB,
 async ({ t3, app, browser, screen }) => {
  const originalProject = await t3.project("repo");
  const fixture = `${process.env.EVIDENCE_SCRATCH}/run-${randomUUID()}`;
  mkdirSync(fixture);
  const project = `${fixture}/repo`;
  const projectId = execFileSync("sqlite3", ["-readonly", `${T3_HOME}/userdata/statev2.sqlite`, "SELECT project_id FROM projection_projects WHERE title = 'repo'"], { encoding: "utf8" }).trim();
  cpSync(originalProject, project, { recursive: true });
  await runPromise(Effect.gen(function*() {
   const client = yield* rpcClient(T3_HOME, app.baseUrl!);
   yield* client["projects.mutate"]({ type: "project.update", commandId: CommandId.make(randomUUID()), projectId: ProjectId.make(projectId), workspaceRoot: project });
  }).pipe(Effect.scoped));
  const other = await t3.project("notes");
  const active = await t3.thread({ project: other, title: "Import verification", messages: ["Start"] });
  symlinkSync(git, `${T3_HOME}/bin/git`);
  execFileSync(git, ["-C", project, "refs", "migrate", "--ref-format=reftable"]);
  const worktree = `${project}/.claude/worktrees/wt-docs`;
  execFileSync(git, ["-C", project, "worktree", "add", "-b", "docs-refresh", worktree]);
  const claudeHome = `${T3_HOME}/claude-fixture`;
  const sessionId = randomUUID();
  const sessionDir = `${claudeHome}/projects/-repo-worktree`;
  mkdirSync(sessionDir, { recursive: true });
  writeFileSync(`${sessionDir}/${sessionId}.jsonl`, [
   { type: "user", uuid: randomUUID(), sessionId, cwd: worktree, timestamp: new Date().toISOString(), message: { role: "user", content: "Refresh the docs" } },
   { type: "assistant", uuid: randomUUID(), sessionId, cwd: worktree, timestamp: new Date().toISOString(), message: { role: "assistant", content: [{ type: "text", text: "Documentation refreshed." }] } },
  ].map(x => JSON.stringify(x)).join("\n") + "\n");
  await runPromise(Effect.gen(function*() {
   const client = yield* rpcClient(T3_HOME, app.baseUrl!);
   yield* client["server.updateSettings"]({ patch: { providerInstances: { codex: { driver: "codex", enabled: false }, pi: { driver: "pi", enabled: false }, claudeAgent: { driver: "claudeAgent", enabled: true, config: { homePath: claudeHome } } } } });
  }).pipe(Effect.scoped));
  await t3.open(active);
  await screen.getByRole("textbox").waitFor();
  const initial = await runPromise(Effect.gen(function*() {
   const client = yield* rpcClient(T3_HOME, app.baseUrl!);
   const scan = yield* client["agentSessions.scan"]({});
   console.log("Scan:", JSON.stringify(scan));
   const candidate = scan.candidates.find(x => x.path === project)!;
   yield* client["agentSessions.import"]({ projectId: ProjectId.make(candidate.projectId!), expectedWorkspaceRoot: project });
   return execFileSync("sqlite3", ["-readonly", "-json", `${T3_HOME}/userdata/statev2.sqlite`, "SELECT title, json_extract(payload_json, '$.branch') AS branch FROM orchestration_v2_projection_threads WHERE title = 'Refresh the docs'"], { encoding: "utf8" });
  }).pipe(Effect.scoped));
  await browser.evaluate(() => { document.dispatchEvent(new KeyboardEvent("keydown", { key: "k", code: "KeyK", ctrlKey: true, bubbles: true })); return null; });
  await screen.getByRole("combobox").fill("Refresh the docs");
  await screen.getByText("Refresh the docs", { exact: true }).waitFor();
  await app.screenshot("imported-worktree-branch");
  console.log("Initial imported thread:", initial);
  expect(JSON.parse(initial)[0]?.branch, "The imported thread must store docs-refresh immediately, before VCS sync").toBe("docs-refresh");
 });
