/// <reference lib="dom" />
import { spawn } from "node:child_process";
import { createServer } from "node:net";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Schedule from "effect/Schedule";
import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
import { APP_DIR } from "../e2e.config.ts";
import { SECOND_HOME } from "./second-server.ts";
import { prepareHome } from "./start-app.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

// All forge responses are real. SIGSTOP/SIGKILL interrupts only our linked server.
test("Failed linked pagination remains retryable while local pagination continues", WEB, async ({t3, app, screen, browser}) => {
  const reservation = createServer();
  await new Promise<void>(resolve => reservation.listen(0, "127.0.0.1", resolve));
  const port = (reservation.address() as {port:number}).port;
  await new Promise<void>(resolve => reservation.close(() => resolve()));
  await runPromise(prepareHome(SECOND_HOME));
  const host = `http://127.0.0.1:${port}`;
  let child: ReturnType<typeof spawn>;
  const start = () => new Promise<string>((resolve, reject) => {
    child = spawn(process.execPath, ["apps/server/src/bin.ts", "serve", "--host", "127.0.0.1", "--port", String(port), "--base-dir", SECOND_HOME, "--dev-url", app.baseUrl], {
      cwd: APP_DIR, env: {...process.env, T3CODE_DEV_SEED:"0", T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD:"0", T3CODE_ENVIRONMENT_LABEL:"Linked", T3CODE_ENVIRONMENT_MACHINE_KIND:"laptop"}, stdio:["ignore","pipe","pipe"]
    });
    let output = "";
    child.stdout!.on("data", data => {
      output += data.toString();
      const token = /^Token:\s*(\S+)/m.exec(output)?.[1];
      if (token) resolve(token);
    });
    child.once("error", reject);
    child.once("exit", code => reject(new Error(`Linked server exited ${code}`)));
  });
  const ready = () => runPromise(HttpClient.get(`${host}/.well-known/t3/environment`).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.retry({schedule: Schedule.spaced("50 millis"), times: 200}), Effect.provide(FetchHttpClient.layer)));
  const stop = async () => {
    if (child.exitCode !== null || child.signalCode !== null) return;
    const done = new Promise<void>(resolve => child.once("exit", () => resolve()));
    child.kill("SIGKILL");
    await done;
  };
  try {
    const token = await start();
    await ready();
    const remoteConfig = (url: string) => ({".git/config": `[remote "origin"]\n url = ${url}\n fetch = +refs/heads/*:refs/remotes/origin/*\n`});
    await t3.project("Local reviews", remoteConfig("https://github.com/pingdotgg/t3code.git"));
    await makeState(SECOND_HOME).state.project("Linked reviews", remoteConfig("https://gitlab.com/gitlab-org/gitlab.git"));
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    await screen.getByRole("heading", "Backend added", {exact:true}).waitFor();
    await app.open("/pull-requests?state=open&involvement=all");
    // Read and operate on real DOM buttons: the snapshot node budget can omit the footer
    // once hundreds of actual pull requests (and their labels) have loaded.
    const rows = () => browser.evaluate(() => {
      const buttons = Array.from(document.querySelectorAll("button"));
      return {local:buttons.filter(b=>b.textContent?.includes("pingdotgg/t3code")).length,
        remote:buttons.filter(b=>b.textContent?.includes("gitlab-org/gitlab")).length};
    });
    const wait = (condition: "healthy" | "loading" | "failed" | "local" | "remote", previous=0) => browser.evaluate(({condition,previous}) => new Promise<void>(resolve => {
      const check = () => {
        const buttons = Array.from(document.querySelectorAll("button"));
        const button = (text:string) => buttons.find(b=>b.textContent?.trim()===text);
        const loading = Array.from(document.querySelectorAll("span")).some(e=>e.textContent?.trim()==="Loading more");
        const local = buttons.filter(b=>b.textContent?.includes("pingdotgg/t3code")).length;
        const remote = buttons.filter(b=>b.textContent?.includes("gitlab-org/gitlab")).length;
        const done = condition === "healthy" ? local>=99 && remote>=99 && !!button("Load more pull requests") && !loading
          : condition === "loading" ? loading
          : condition === "failed" ? !!button("Retry") && !loading && local>previous
          : condition === "local" ? local>previous && !loading
          : remote>previous && !loading;
        if(done) {observer.disconnect(); resolve();}
      };
      const observer = new MutationObserver(check);
      observer.observe(document.body,{childList:true,subtree:true,attributes:true,characterData:true});
      check();
    }), {condition,previous});
    const click = (text:string) => browser.evaluate(text => {
      const button=Array.from(document.querySelectorAll("button")).find(b=>b.textContent?.trim()===text);
      if(!button) throw new Error(`Missing ${text}`);
      button.scrollIntoView({block:"center"}); button.click();
    },text);
    const footer = () => browser.evaluate(() => {
      const buttons=Array.from(document.querySelectorAll("button"));
      const target=buttons.find(b=>b.textContent?.trim()==="Load more pull requests") ?? buttons.find(b=>b.textContent?.trim()==="Retry") ?? buttons.filter(b=>b.textContent?.includes("pingdotgg/t3code")||b.textContent?.includes("gitlab-org/gitlab")).at(-1);
      target?.scrollIntoView({block:"end"});
    });
    await wait("healthy");
    console.log("initial rows",await rows());
    await app.screenshot("healthy-first-page");
    const first=await rows();
    child.kill("SIGSTOP");
    await click("Load more pull requests");
    await wait("loading");
    await stop();
    await wait("failed",first.local);
    await footer();
    console.log("failed continuation rows",await rows());
    await app.screenshot("linked-continuation-failed");
    const second=await rows();
    await click("Load more pull requests");
    await wait("local",second.local);
    await footer();
    console.log("healthy continuation rows",await rows());
    await app.screenshot("after-healthy-load-more");
    await start();
    await ready();
    try {
      const retry = await browser.evaluate(() => Array.from(document.querySelectorAll("button")).some(b=>b.textContent?.trim()==="Retry"));
      expect(retry).toBe(true);
      const before = await rows();
      await click("Retry");
      await wait("remote",before.remote);
      const after = await rows();
      console.log("recovered rows",after);
      expect(after.remote).toBeGreaterThan(before.remote);
    } finally {
      await footer();
      await app.screenshot("recovered-linked-pagination");
    }
  } finally { await stop(); }
});
