import { execFileSync } from "node:child_process";
import { writeFileSync, utimesSync, readFileSync } from "node:fs";
import { randomUUID } from "node:crypto";
import { CommandId, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { expect } from "e2e";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const org = process.env.AZURE_DEVOPS_TEST_ORG!;
const projectName = process.env.AZURE_DEVOPS_TEST_PROJECT!;
const repo = "t3-factory-test";
const remote = `${org}/${encodeURIComponent(projectName)}/_git/${repo}`;
const az = (args: string[]) => execFileSync("az", [...args, "--organization", org, ...(args[2] === "update" ? [] : ["--project", projectName]), "-o", "json"], { encoding: "utf8" });
const clock = process.env.PROOF_CLOCK_FILE!;
const git = (cwd: string, args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" });
const helper = '!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f';

test("An inactive thread stays active when its branch has an unrecorded open PR", WEB, async ({t3, app, screen, browser}) => {
  writeFileSync(clock, "0");
  const tag = `proof-41116-${randomUUID().slice(0, 8)}`;
  const base = `${tag}-base`, feature = `${tag}-feature`;
  const workspace = await t3.project("Open PR retention", {"README.md": "Synthetic proof project\n"});
  let pr: number | undefined;
  let pushed = false;
  try {
    git(workspace, ["remote", "add", "origin", remote]);
    git(workspace, ["config", "credential.helper", helper]);
    git(workspace, ["checkout", "-b", base]);
    git(workspace, ["checkout", "-b", feature]);
    writeFileSync(`${workspace}/feature.txt`, "Keep this branch active while its PR is open.\n");
    git(workspace, ["add", "."]);
    git(workspace, ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Add feature"]);
    git(workspace, ["-c", `credential.helper=${helper}`, "push", "-u", "origin", base, feature]);
    pushed = true;
    const thread = await t3.thread({project: workspace, title: "Idle work with an open PR", messages: ["go"], model: "multi-turn"});
    const rpc = <A>(f: (client: any) => Effect.Effect<A, any, any>) => runPromise(Effect.gen(function*() { const client = yield* rpcClient(T3_HOME, app.baseUrl!); return yield* f(client); }).pipe(Effect.scoped) as any) as Promise<A>;
    const projection = () => rpc<any>(c => c["orchestration.getThreadProjection"]({threadId: ThreadId.make(thread.threadId)}));
    await rpc(c => c["orchestration.dispatchCommand"]({type:"thread.unpin", commandId:CommandId.make(randomUUID()), threadId:ThreadId.make(thread.threadId)}));
    await rpc(c => c["server.updateSettings"]({patch:{sidebarAutoSettleAfterDays:null, sidebarAutoSettleKeepPullRequests:true, sidebarAutoSettleOnMerge:false}}));
    await t3.open(thread);
    await screen.getByText("fixture turn complete", {exact:false}).waitFor();
    const before = await projection();
    if (before.thread.branchPullRequest || before.thread.pullRequests?.length) throw new Error("PR was already recorded before creation");
    pr = JSON.parse(az(["repos","pr","create","--repository",repo,"--source-branch",feature,"--target-branch",base,"--title","Open PR retention proof","--description","Synthetic inactivity retention proof."])).pullRequestId;
    await rpc(c => c["server.updateSettings"]({patch:{sidebarAutoSettleAfterDays:1, sidebarAutoSettleKeepPullRequests:true}}));
    const runtimePath = `${T3_HOME}/userdata/server-runtime.json`;
    const previousStart = JSON.parse(readFileSync(runtimePath, "utf8")).startedAt;
    writeFileSync(clock, String(3 * 24 * 60 * 60 * 1000));
    // The dev watch launcher restarts the same real server after a source timestamp changes.
    const now = new Date();
    utimesSync(`${APP_DIR}/apps/server/src/bin.ts`, now, now);
    const restartDeadline = Date.now() + 30_000;
    while (Date.now() < restartDeadline) {
      try { if (JSON.parse(readFileSync(runtimePath, "utf8")).startedAt !== previousStart) break; } catch {}
      await new Promise(r => setTimeout(r, 250));
    }
    await t3.open(thread);
    // Wait for real branch discovery, then let the settings-triggered settlement sweep finish.
    const deadline = Date.now() + 100_000;
    while (Date.now() < deadline) {
      const p = await projection();
      if (p.thread.branchPullRequest != null || p.thread.pullRequests?.some((x:any) => x.snapshot?.state === "open")) break;
      await new Promise(r => setTimeout(r, 500));
    }
    await new Promise(r => setTimeout(r, 5000));
    const details = screen.getByRole("button", "Toggle thread details panel");
    const isOpen = await browser.evaluate(() => document.querySelector('[aria-label="Toggle thread details panel"]')?.getAttribute("aria-pressed"));
    if (isOpen !== "true") await details.tap();
    await screen.getByText("Open PR retention proof", {exact:false}).first().waitFor({timeout:30_000});
    await app.screenshot("idle-thread-open-pr");
    const after = await projection();
    console.log("PROOF_STATE", JSON.stringify({branch:after.thread.branch, settledOverride:after.thread.settledOverride, settledAt:after.thread.settledAt, branchPullRequest:after.thread.branchPullRequest, pullRequests:after.thread.pullRequests, createdAt:after.thread.createdAt}));
    await expect(after.thread.settledAt ?? null).toBeNull();
  } finally {
    writeFileSync(clock, "0");
    if(pr) az(["repos","pr","update","--id",String(pr),"--status","abandoned"]);
    if(pushed) git(workspace,["-c",`credential.helper=${helper}`,"push","origin","--delete",base,feature]);
  }
});
