import { execFileSync } from "node:child_process";
import { renameSync, mkdirSync, cpSync } from "node:fs";
import { randomUUID } from "node:crypto";
import { ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Scheduled runs preserve explicitly selected tracked repository worktrees", WEB, async ({ t3, app, screen, browser }) => {
  const originalProject = await t3.project("project");
  const runRoot = `${process.env.T3_PROOF_ROOT}/${randomUUID()}`;
  mkdirSync(runRoot, {recursive: true});
  const project = `${runRoot}/project`;
  cpSync(originalProject, project, {recursive: true});
  const api = await t3.project("api", { "api.txt": "Tracked API repository\n" });
  const cli = (args: string[]) => runPromise(makeState(T3_HOME).cli(args));
  const token = (await cli(["auth", "session", "issue", "--token-only"])).stdout.trim();
  const headers = { authorization: `Bearer ${token}`, "content-type": "application/json" };
  const { projects } = await (await fetch(`${app.baseUrl}/api/projects`, { headers })).json();
  const projectId = projects.find((p: { workspaceRoot: string }) => p.workspaceRoot === originalProject).id;
  const updated = await fetch(`${app.baseUrl}/api/projects/mutate`, { method: "POST", headers, body: JSON.stringify({ type: "project.update", commandId: randomUUID(), projectId, workspaceRoot: project, trackedFolders: [{name: "api", path: api}] }) });
  if (!updated.ok) throw new Error(`Project setup: ${updated.status} ${await updated.text()}`);
  const strategy = { type: "worktree" as const, baseRef: "main", startFromOrigin: true, repositories: [{path: api}] };
  const save = (title: string) => runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    return yield* client["scheduledTasks.upsert"]({ title, prompt: "Describe this workspace", enabled: false, schedule: {type: "interval", everyMs: 3600000}, projectId, threadMode: "new_thread", workspaceStrategy: strategy, modelSelection: {instanceId: ProviderInstanceId.make("devReplay"), model: "multi-turn"}, runtimeMode: "full-access", interactionMode: "default" });
  }).pipe(Effect.scoped));
  await save("Task A");
  renameSync(`${project}/.git`, `${project}/git-moved-aside`);
  const savedB = await save("Task B");
  await t3.open("/settings/scheduled-tasks");
  await screen.getByRole("button", "Actions for Task A").tap();
  await screen.getByRole("menuitem", "Run now").tap();
  await screen.getByText("Succeeded", {exact: true}).waitFor({timeout: 60000});
  await app.screenshot("scheduled-run-completed");
  const listed = JSON.parse((await cli(["thread", "list", "--project", project, "--json"])).stdout);
  const thread = listed.find((t: {title: string}) => t.title === "Task A");
  if (!thread) throw new Error("Scheduled Task A did not create a thread");
  await t3.open({threadId: thread.threadId});
  await screen.getByText("first fixture turn complete", {exact: true}).waitFor();
  const detailsVisible = await browser.evaluate(() => document.querySelector('[aria-label="Toggle thread details panel"]')?.getAttribute("aria-pressed") === "true");
  if (!detailsVisible) await screen.getByRole("button", "Toggle thread details panel", {exact: true}).tap();
  await screen.getByText(/Repositories appear here once this thread changes them\.|^api$/).waitFor();
  await screen.getByText("Syncing messages...", {exact: true}).waitFor({state: "hidden"});
  await app.screenshot("scheduled-thread-repositories");
  const details = JSON.parse((await cli(["thread", "show", thread.threadId, "--json"])).stdout);
  const worktrees = execFileSync("git", ["-C", api, "worktree", "list", "--porcelain"], {encoding: "utf8"});
  await expect(savedB.task.workspaceStrategy).toEqual(strategy);
  await expect(JSON.stringify(details)).toContain("worktreePath");
  const threadRow = JSON.parse(execFileSync("sqlite3", ["-readonly", "-json", `${T3_HOME}/userdata/statev2.sqlite`, `select json_extract(payload_json, '$.worktreePath') as worktree_path from orchestration_v2_projection_threads where thread_id = '${thread.threadId}'`], {encoding: "utf8"}))[0];
  await expect(Boolean(threadRow.worktree_path)).toEqual(true);
  await expect(worktrees).toContain("refs/heads/t3/");
});
