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

test("Manual cleanup retries the recovered GitLab API immediately", WEB, async ({t3,app,screen}) => {
  const project = await t3.project("cleanup-retry");
  const git = (...args:string[]) => execFileSync("git", args, {cwd:project,encoding:"utf8"});
  const api = (...args:string[]) => JSON.parse(execFileSync("/usr/bin/glab",["api",...args],{encoding:"utf8"}));
  const branch = `cleanup-${Date.now()}`;
  const remote = "https://gitlab.com/julius54/cleanup-proof-47484.git";
  git("remote","add","origin",remote);
  git("fetch","origin","main");
  git("reset","--hard","origin/main");
  git("branch","--set-upstream-to=origin/main","main");
  git("remote","set-head","origin","main");
  const launch = () => runPromise(makeState(T3_HOME).cli(["thread","start",project,"Start", "--worktree","main","--branch",branch,"--provider","devReplay","--model","multi-turn","--wait","--json"]));
  const started = await launch().catch(error => {
    if (!String(error).includes("Advertised models: default")) throw error;
    return launch();
  });
  const thread = JSON.parse(started.stdout);
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    const projection = yield* client["orchestration.getThreadProjection"]({threadId: ThreadId.make(thread.threadId)});
    for (const session of projection.providerSessions) {
      yield* client["orchestration.dispatchCommand"]({type:"provider-session.detach", commandId:CommandId.make(randomUUID()), threadId:ThreadId.make(thread.threadId), providerSessionId:session.id,reason:"scenario setup"});
    }
  }).pipe(Effect.scoped));
  git("push","origin",branch);
  // A real commit and real merged MR are required by cleanup's reachability safeguards.
  const worktrees = git("worktree","list","--porcelain");
  const worktree = worktrees.split("\n\n").find(x=>x.includes(`branch refs/heads/${branch}`))!.split("\n")[0]!.slice(9);
  writeFileSync(`${worktree}/sample.txt`,branch);
  execFileSync("git",["add","sample.txt"],{cwd:worktree});
  execFileSync("git",["-c","user.name=Scenario","-c","user.email=scenario@example.invalid","commit","--allow-empty","-m","Cleanup sample"],{cwd:worktree});
  git("push","origin",branch);
  const mr = api("-X","POST","projects/89772184/merge_requests","-f",`source_branch=${branch}`,"-f","target_branch=main","-f","title=Cleanup recovery sample");
  for (let check = 0; check < 20; check++) {
    const ready = api(`projects/89772184/merge_requests/${mr.iid}?with_merge_status_recheck=true`);
    if (ready.detailed_merge_status === "mergeable") break;
    if (check === 19) throw new Error("GitLab MR did not become mergeable");
  }
  api("-X","PUT",`projects/89772184/merge_requests/${mr.iid}/merge`,"-f","should_remove_source_branch=false");
  const outage = `${T3_HOME}/api-offline`;
  const calls = `${T3_HOME}/glab-calls.log`;
  const wrapper = `${T3_HOME}/bin/glab`;
  writeFileSync(wrapper, `#!/bin/sh\nprintf '%s\\n' "$*" >> '${calls}'\nif [ -f '${outage}' ] && [ "$1" = mr ]; then\n  HTTPS_PROXY=http://127.0.0.1:1 HTTP_PROXY=http://127.0.0.1:1 NO_PROXY= /usr/bin/glab "$@"\nelse\n  exec /usr/bin/glab "$@"\nfi\n`);
  chmodSync(wrapper,0o755);
  await t3.open(thread);
  await t3.open("/settings/worktrees");
  writeFileSync(outage,"");
  await screen.getByRole("switch","Delete merged worktrees",{exact:true}).tap();
  await t3.open("/settings/maintenance");
  const cleanup = screen.getByRole("button","Delete now",{exact:true});
  await cleanup.tap();
  await screen.getByRole("button",/^Last run.*1 failed/).waitFor();
  await screen.getByRole("button","Deleting…",{exact:true}).waitFor({state:"hidden"});
  const dismiss = screen.getByRole("button", "Dismiss notification");
  if (await dismiss.isVisible()) await dismiss.tap();
  await dismiss.waitFor({state:"hidden"});
  await app.screenshot("api-unavailable-first-cleanup");
  unlinkSync(outage);
  // Verify recovery through the actual CLI before the immediate user retry.
  api(`projects/89772184/merge_requests/${mr.iid}`);
  const callsBefore = readFileSync(calls,"utf8").split("\n").filter(x=>x.startsWith("mr list")).length;
  await cleanup.tap();
  await screen.getByRole("button","Deleting…",{exact:true}).waitFor({state:"hidden"});
  try {
    await expect(screen.getByRole("button",/^Last run.*1 removed, 0 kept/)).toBeVisible();
    expect(existsSync(worktree)).toBe(false);
    expect(readFileSync(calls,"utf8").split("\n").filter(x=>x.startsWith("mr list")).length > callsBefore).toBe(true);
  } finally {
    if (await dismiss.isVisible()) await dismiss.tap();
    await dismiss.waitFor({state:"hidden"});
    await app.screenshot("immediate-retry-after-api-recovery");

  }
});
