/// <reference lib="dom" />
import { execFileSync } from "node:child_process";
import { readFileSync, writeFileSync, utimesSync, realpathSync } from "node:fs";
import { ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const command = (cmd: string, args: string[], cwd?: string) => execFileSync(cmd, args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
const org = process.env.AZURE_DEVOPS_TEST_ORG!;
const azureProject = process.env.AZURE_DEVOPS_TEST_PROJECT!;
const az = (...args: string[]) => JSON.parse(command("az", [...args, "--organization", org, ...(args[2] === "update" ? [] : ["--project", azureProject]), "-o", "json"]));
const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
async function until<T>(read: () => Promise<T>, done: (value: T) => boolean) {
  for (let attempt = 0; attempt < 120; attempt++) {
    const value = await read();
    if (done(value)) return value;
    await pause(500);
  }
  throw new Error("Setup did not reach the requested real-app state");
}

test("A reused Azure branch with a new open PR stays active after restart", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("azure-repro");
  const repo = az("repos", "list")[0];
  const remote = new URL(repo.remoteUrl); remote.username = "";
  const git = (...args: string[]) => command("git", args, project);
  const auth = ["-c", 'credential.helper=!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f'];
  const branch = `repro-49347-${Date.now()}`;
  const prs: number[] = [];
  const withClient = <A, E>(use: (client: Effect.Success<ReturnType<typeof rpcClient>>) => Effect.Effect<A, E>) => runPromise(rpcClient(T3_HOME, app.baseUrl ?? "").pipe(Effect.flatMap(use), Effect.scoped));
  const settings = (patch: Record<string, unknown>) => withClient(client => client["server.updateSettings"]({ patch }));
  let stopped = false;
  const restart = () => { const entry = `${APP_DIR}/apps/server/src/bin.ts`; const now = new Date(); utimesSync(entry, now, now); stopped = false; };
  try {
    await settings({ sidebarAutoSettleOnMerge: false, sidebarAutoSettleAfterDays: null });
    git("remote", "add", "origin", remote.toString());
    git("config", "credential.helper", auth[1].split("credential.helper=")[1]);
    git(...auth, "fetch", "origin", "main");
    git("reset", "--hard", "FETCH_HEAD");
    git("switch", "-c", branch);
    const commit = (message: string) => git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--allow-empty", "-m", message);
    commit("Reused branch first change");
    git(...auth, "push", "-u", "origin", branch);
    const createPR = (title: string) => { const pr = az("repos", "pr", "create", "--repository", repo.id, "--source-branch", branch, "--target-branch", "main", "--title", title); prs.push(pr.pullRequestId); return pr.pullRequestId as number; };
    const first = createPR("Reused branch PR A");
    const thread = await t3.thread({ project, title: "Reused branch repro", messages: ["Start"] });
    const projection = () => withClient(client => client["orchestration.getThreadProjection"]({ threadId: ThreadId.make(thread.threadId) }));
    await t3.open(thread);
    await until(projection, value => value.thread.branchPullRequest?.number === first);
    await screen.getByRole("heading", "Reused branch repro", { exact: true }).waitFor();
    await screen.getByRole("button", new RegExp(`Pull request #${first}, open:`)).waitFor();
    await pause(1500);
    await app.screenshot("first-auto-detected-open-pr");

    const runtimePath = `${T3_HOME}/userdata/server-runtime.json`;
    const runtime = JSON.parse(readFileSync(runtimePath, "utf8"));
    const port = new URL(runtime.origin).port;
    const listeners = command("ss", ["-H", "-ltnp", `sport = :${port}`]);
    const pid = Number(/pid=(\d+)/.exec(listeners)?.[1]);
    if (!pid || realpathSync(`/proc/${pid}/cwd`) !== realpathSync(`${APP_DIR}/apps/server`)) throw new Error("Could not confirm owned server PID");
    process.kill(pid, "SIGTERM"); stopped = true;
    await until(async () => command("ss", ["-H", "-ltn", `sport = :${port}`]), value => value === "");
    const settingsPath = `${T3_HOME}/userdata/settings.json`;
    const saved = JSON.parse(readFileSync(settingsPath, "utf8"));
    writeFileSync(settingsPath, JSON.stringify({ ...saved, sidebarAutoSettleOnMerge: true, sidebarAutoSettleAfterDays: null }));
    az("repos", "pr", "update", "--id", String(first), "--status", "abandoned");
    commit("Reused branch second change");
    git(...auth, "push", "origin", branch);
    const second = createPR("Reused branch PR B");
    restart();
    await until(async () => { try { return JSON.parse(readFileSync(runtimePath, "utf8")).startedAt; } catch { return runtime.startedAt; } }, value => value !== runtime.startedAt);
    await t3.open(thread);
    await until(projection, value => value.thread.branchPullRequest?.number === second);
    // Observe the startup settlement sweep after the branch PR refresh, as in the report.
    await pause(8000);
    const result = await projection();
    await browser.evaluate(() => { localStorage.setItem("t3code:sidebar:settled-expanded", "true"); return null; });
    await t3.open(thread);
    await screen.getByRole("heading", "Reused branch repro", { exact: true }).waitFor();
    await screen.getByRole("button", new RegExp(`Pull request #${second}, open:`)).waitFor();
    await pause(1500);
    await app.screenshot("new-open-pr-after-restart");
    expect(result.thread.settledOverride).not.toBe("settled");
  } finally {
    if (stopped) restart();
    for (const id of prs) { try { az("repos", "pr", "update", "--id", String(id), "--status", "abandoned"); } catch {} }
    try { git(...auth, "push", "origin", "--delete", branch); } catch {}
  }
});
