/// <reference lib="dom" />
import { createHash } from "node:crypto";
import { EnvironmentHttpApi } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { FetchHttpClient } from "effect/http";
import * as HttpApiClient from "effect/http-api/HttpApiClient";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { environmentId, makeState, runPromise, test, WEB } from "./t3.ts";

test("A real GitHub PR line link reveals line 700 after a lost full-file read", WEB, async ({t3, app, browser}) => {
  const workspace = await t3.project("PR line recovery");
  await runPromise(run("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], {cwd: workspace}));
  const origin = app.baseUrl!;
  const environment = await runPromise(environmentId(origin));
  const project = await runPromise(Effect.gen(function* () {
    const {stdout} = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
    const client = yield* HttpApiClient.make(EnvironmentHttpApi, {baseUrl: origin});
    const {projects} = yield* client.projects.snapshot({headers: {authorization: `Bearer ${stdout.trim()}`}});
    return projects.find(p => p.workspaceRoot === workspace)!;
  }).pipe(Effect.provide(FetchHttpClient.layer)));
  const path = "packages/client-runtime/src/state/pullRequests.ts";
  const digest = createHash("sha256").update(path).digest("hex");
  const query = new URLSearchParams({repository: "pingdotgg/t3code", number: "47643", selectedProjectId: project.id, selectedEnvironmentId: environment, selectedHost: "github.com", selectedUrl: `https://github.com/pingdotgg/t3code/pull/47643/files#diff-${digest}R700`});
  const route = `/pull-requests?${query}`;
  await browser.emulateMedia({colorScheme: "dark", reducedMotion: "reduce"});
  await browser.addInitScript(() => {
    const state = {armed: false, dropped: false, reads: 0, reconnected: false};
    (window as any).__proof = state;
    let lost: WebSocket | undefined;
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (lost && this !== lost && this.readyState === 1) state.reconnected = true;
      if (typeof data === "string" && data.includes('"tag":"pullRequests.diffFileContents"')) {
        state.reads++;
        if (state.armed && !state.dropped) {
          state.dropped = true; lost = this;
          this.close(4000, "Proof: interrupted file read");
          return;
        }
      }
      return send.call(this, data);
    };
  });
  const lineState = () => browser.evaluate(() => {
    for (const view of document.querySelectorAll(".diff-render-surface")) {
      for (const host of view.querySelectorAll("diffs-container")) {
        const line = host.shadowRoot?.querySelector('[data-line="700"]');
        if (!line) continue;
        const row = line.getBoundingClientRect();
        const bounds = view.getBoundingClientRect();
        return {text: line.textContent?.trim(), inView: row.height > 0 && row.top >= Math.max(0,bounds.top) && row.bottom <= Math.min(innerHeight,bounds.bottom), top: row.top};
      }
    }
    return {inView:false};
  });
  await t3.open("/");
  await browser.evaluate((route) => {history.pushState({}, "", route); dispatchEvent(new PopStateEvent("popstate")); return null;}, route);
  await runPromise(Effect.sleep("15 seconds"));
  await app.screenshot("control-no-interruption");
  if (!(await lineState()).inView) throw new Error("Control failed: linked line 700 was not in view without interruption");
  await t3.open("/");
  await browser.evaluate((route) => {(window as any).__proof.armed = true; history.pushState({}, "", route); dispatchEvent(new PopStateEvent("popstate")); return null;}, route);
  await runPromise(Effect.sleep("40 seconds"));
  await app.screenshot("linked-line-after-reconnect");
  const fault = await browser.evaluate(() => (window as any).__proof);
  if (!fault.dropped || !fault.reconnected) throw new Error(`Fault did not run and reconnect: ${JSON.stringify(fault)}`);
  await expect.poll(async () => (await lineState()).inView).toBe(true);
});
