import { execFile as execFileCallback } from "node:child_process";
import { promisify } from "node:util";
import { writeFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { CommandId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const execFile = promisify(execFileCallback);
const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const az = async (...args: string[]) => JSON.parse((await execFile("az", [...args, "--organization", process.env.AZURE_DEVOPS_TEST_ORG!, "--output", "json"])).stdout || "null");

test("A running stop-on-settle action allows automatic settlement after merge", WEB, async ({ t3, app, screen, browser }) => {
  const cwd = await t3.project("Settlement demo");
  const tag = `proof-40489-${randomUUID().slice(0, 8)}`;
  const base = `${tag}-base`;
  const feature = `${tag}-feature`;
  const repos = await az("repos", "list", "--project", process.env.AZURE_DEVOPS_TEST_PROJECT!);
  const repo = repos[0];
  const git = (...args: string[]) => execFile("git", args, { cwd });
  const push = (...args: string[]) => git("-c", 'credential.helper=!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f', "push", "origin", ...args);
  await git("remote", "add", "origin", repo.remoteUrl);
  await git("branch", base);
  await git("switch", "-c", feature);
  await writeFile(`${cwd}/feature.txt`, "Synthetic settlement proof\n");
  await git("add", "feature.txt");
  await git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Add synthetic feature");
  await push(`${base}:${base}`, `${feature}:${feature}`);
  let pr: any;
  try {
    pr = await az("repos", "pr", "create", "--project", process.env.AZURE_DEVOPS_TEST_PROJECT!, "--repository", repo.id, "--source-branch", feature, "--target-branch", base, "--title", "Settlement proof 40489");
    const thread = await t3.thread({ project: cwd, title: "Stop-on-settle action", messages: ["Finish the synthetic feature"], model: "multi-turn" });
    const control = await t3.thread({ project: cwd, title: "Ordinary busy terminal control", messages: ["Finish the synthetic feature"], model: "multi-turn" });
    const origin = app.baseUrl ?? "";
    const rpc = <A>(fn: (client: any) => Effect.Effect<A, any, any>) => runPromise(Effect.gen(function* () { const client = yield* rpcClient(T3_HOME, origin); return yield* fn(client); }).pipe(Effect.scoped));
    await rpc((client) => client["server.updateSettings"]({ patch: { sidebarAutoSettleOnMerge: true, defaultProjectScripts: [{ id: "dev-server", name: "Dev server", command: "printf '\\033[2J\\033[H'; python3 -u -m http.server 18789", icon: "play", runOnWorktreeCreate: false, stopOnSettle: true }] } }));
    await t3.open(thread);
    await screen.getByRole("button", "Run Dev server", { exact: true }).tap();
    await pause(2000);
    await rpc((client) => Effect.gen(function* () {
      const threadId = ThreadId.make(control.threadId);
      yield* client["terminal.open"]({ threadId, terminalId: "ordinary-server", cwd, stopOnSettle: false, env: { PS1: "$ " } });
      yield* client["terminal.write"]({ threadId, terminalId: "ordinary-server", data: "printf '\\033[2J\\033[H'; python3 -u -m http.server 18790\r" });
    }));
    await app.screenshot("running-before-merge");
    await az("repos", "pr", "update", "--id", String(pr.pullRequestId), "--status", "completed", "--merge-commit-message", "Merge synthetic settlement proof");
    // Observe the real minute-cadence sweep, allowing a second sweep for the host refresh.
    await pause(135000);
    await app.screenshot("after-automatic-settlement");
    const projection: any = await rpc((client) => client["orchestration.getThreadProjection"]({ threadId: ThreadId.make(thread.threadId) }));
    const controlProjection: any = await rpc((client) => client["orchestration.getThreadProjection"]({ threadId: ThreadId.make(control.threadId) }));
    await t3.open(control);
    await screen.getByText("first fixture turn complete", { exact: true }).waitFor();
    if (!(await browser.locator(".xterm").isVisible())) await screen.getByRole("button", "Toggle terminal drawer").tap();
    await pause(1000);
    await app.screenshot("ordinary-terminal-stays-open");
    await t3.open(thread);
    await screen.getByText("first fixture turn complete", { exact: true }).waitFor();
    const response = await fetch("http://127.0.0.1:18789").then(() => true, () => false);
    expect({ settled: projection.thread.settledAt !== null, actionStillServing: response, ordinaryTerminalSettled: controlProjection.thread.settledAt !== null }).toEqual({ settled: true, actionStillServing: false, ordinaryTerminalSettled: false });
  } finally {
    if (pr) await az("repos", "pr", "update", "--id", String(pr.pullRequestId), "--status", "abandoned").catch(() => {});
    await push("--delete", base, feature);
  }
});
