import { execFileSync } from "node:child_process";
import { writeFileSync } from "node:fs";
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 projectId = 89906431;
const repository = "julius54/watch-rerun-proof-32276-1796474556";
const gitlab = (endpoint: string, method = "GET", body?: object) => JSON.parse(execFileSync("glab", ["api", `projects/${projectId}/${endpoint}`, "-X", method, ...(body ? ["--input", "-"] : [])], {input: body ? JSON.stringify(body) : undefined, encoding: "utf8"}) || "null");
const pause = (ms: number) => new Promise(r => setTimeout(r, ms));
async function until<T>(label: string, read: () => Promise<T>, accepts: (x: T) => boolean, limit = 600_000): Promise<T> {
  const deadline = Date.now() + limit;
  while (Date.now() < deadline) {
    const value = await read();
    if (accepts(value)) { console.log(label); return value; }
    await pause(5000);
  }
  throw new Error(`Timed out: ${label}`);
}

test("A successful rerun on the same head sends no second checks-passed wake", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("CI rerun proof");
  const git = (...args: string[]) => execFileSync("git", args, {cwd: project, encoding: "utf8"}).trim();
  git("remote", "add", "origin", `https://gitlab.com/${repository}.git`);
  git("fetch", "origin", "main");
  git("reset", "--hard", "origin/main");
  const branch = `proof-${Date.now()}`;
  git("switch", "-c", branch);
  writeFileSync(`${project}/.gitlab-ci.yml`, "check:\n  image: alpine:3.20\n  script:\n    - sleep 150\n    - echo check-passed\n");
  git("add", ".gitlab-ci.yml");
  git("-c", "user.name=Proof", "-c", "user.email=proof@example.invalid", "commit", "-m", "Add real CI check");
  git("push", "-u", "origin", branch);
  const mr = gitlab("merge_requests", "POST", {source_branch: branch, target_branch: "main", title: "CI rerun proof"});
  try {
    await until("initial pipeline passed", async () => gitlab(`pipelines?ref=${branch}`), rows => rows[0]?.status === "success");
    const input = {project, title: "Watch CI rerun", messages: ["Monitor CI on this merge request."]};
    const thread = await t3.thread({...input, model: "default"}).catch((e: unknown) => {
      if (!String(e).includes("Model default is not advertised")) throw e;
      return t3.thread(input);
    });
    const threadId = ThreadId.make(thread.threadId);
    const read = () => runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      return yield* client["orchestration.getThreadProjection"]({threadId});
    }).pipe(Effect.scoped));
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["orchestration.dispatchCommand"]({type: "thread.pull-request.watch", commandId: CommandId.make(randomUUID()), threadId, host: "gitlab.com", repository, number: mr.iid, watching: true, until: "merged", link: {url: mr.web_url, source: "agent"}});
    }).pipe(Effect.scoped));
    await browser.setViewport({width: 1440, height: 900});
    await t3.open(thread);
    await until("watch baseline passed", read, p => p.thread.pullRequests?.some(l => l.watch?.passed === true) === true);
    git("-c", "user.name=Proof", "-c", "user.email=proof@example.invalid", "commit", "--allow-empty", "-m", "Move watched head");
    git("push", "origin", branch);
    const head = git("rev-parse", "HEAD");
    await until("new head pending observed", read, p => p.thread.pullRequests?.some(l => l.watch?.headSha === head && l.watch.checksPending === true) === true);
    const wakes = (p: Awaited<ReturnType<typeof read>>) => p.visibleTurnItems.filter(({item}) => item.type === "notification" && item.summary === `#${mr.iid}: checks passed`);
    await until("first checks-passed wake", read, p => wakes(p).length === 1);
    await app.screenshot("first-pass-notification");
    const pipelines = gitlab(`pipelines?ref=${branch}`);
    const jobs = gitlab(`pipelines/${pipelines[0].id}/jobs`);
    gitlab(`jobs/${jobs[0].id}/retry`, "POST");
    await until("same head rerun pending observed", read, p => p.thread.pullRequests?.some(l => l.watch?.headSha === head && l.watch.checksPending === true) === true);
    await app.screenshot("same-head-rerun-pending");
    await until("same head rerun success observed", read, p => p.thread.pullRequests?.some(l => l.watch?.headSha === head && l.watch.checksPending === false && l.watch.passed === true) === true);
    await pause(8000);
    // Bring the latest notification into view on both commits.
    await t3.open(thread);
    await app.screenshot("same-head-after-rerun");
    const final = await read();
    console.log(`same-head pass notifications: ${wakes(final).length}; head: ${head}`);
    expect(wakes(final).length).toBe(1);
  } finally {
    gitlab(`merge_requests/${mr.iid}`, "PUT", {state_event: "close"});
    gitlab(`repository/branches/${encodeURIComponent(branch)}`, "DELETE");
  }
});
