import { readFile, writeFile } from "node:fs/promises";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as NetService from "@t3tools/shared/Net";
import { expect } from "e2e";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";

import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { run, ScenarioError } from "./shell.ts";
import { prepareHome, start } from "./start-app.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

const HOST = "github.scenario.invalid";
const SCOPE = "scenario/demo";
const HOME = `${T3_HOME}-github-issue-links`;

// Install only on the isolated server. The real GitHub adapter still builds and decodes requests.
const upstream = String.raw`
const host = "${HOST}";
const scope = "${SCOPE}";
const viewer = { login: "reader", databaseId: 123 };
const time = "2026-11-20T10:00:00Z";
const pageInfo = { hasNextPage: false, endCursor: null, hasPreviousPage: false, startCursor: null };
const page = (nodes = []) => ({ nodes, totalCount: nodes.length, pageInfo });
const actor = (login) => ({ __typename: "User", login, name: null, id: login, avatarUrl: "" });
const comment = (login, id, body, at) => ({
  __typename: "IssueComment", id, body, createdAt: at, submittedAt: at,
  author: actor(login), url: "https://" + host + "/" + scope + "/pull/42#issuecomment-" + id,
  lastEditedAt: null, isMinimized: false, reactionGroups: [], pullRequestReview: null,
});
const comments = page([
  comment("alice", "1", "The first conversation comment. Heading navigation should land on its author.", "2026-11-20T10:01:00Z"),
  comment("dana", "2", "The next conversation comment. It should be the next heading.", "2026-11-20T10:02:00Z"),
]);
const reviews = page([{ ...comment("bob", "3", "", "2026-11-20T10:03:00Z"),
  __typename: "PullRequestReview", state: "APPROVED", url: "https://" + host + "/" + scope + "/pull/42#pullrequestreview-3" }]);
const thread = { id: "thread-1", path: "src/release.ts", line: 12, diffSide: "RIGHT",
  isResolved: false, isOutdated: false, comments: page([
    { ...comment("carol", "4", "Review thread: please keep the release note concise.", "2026-11-20T10:04:00Z"), __typename: "PullRequestReviewComment",
      url: "https://" + host + "/" + scope + "/pull/42#discussion_r4" },
  ]) };
const pr = {
  __typename: "PullRequest", id: "PR42", number: 42, title: "Release heading navigation", body: "A synthetic pull request for accessibility verification.",
  url: "https://" + host + "/" + scope + "/pull/42", state: "OPEN", isDraft: false,
  author: actor("author"), createdAt: time, updatedAt: time, closedAt: null, mergedAt: null,
  mergeable: "MERGEABLE", mergeStateStatus: "CLEAN", reviewDecision: "APPROVED",
  additions: 1, deletions: 0, changedFiles: 1, mergeCommit: null, mergedBy: null,
  headRefName: "release", baseRefName: "main", headRefOid: "a".repeat(40),
  isCrossRepository: false, maintainerCanModify: true, headRepositoryOwner: { __typename: "Organization", login: "scenario" },
  headRepository: null, headRef: null, autoMergeRequest: null, baseRef: null,
  viewerCanUpdate: false, viewerDidAuthor: false, viewerCanUpdateBranch: false,
  reviewRequests: page(), labels: page(), commits: page(), latestReviews: page(),
  comments, reviews, reviewThreads: page([thread]), reviewDismissals: page(), timelineItems: page(),
  mergeQueueRemovals: page(), reactionGroups: [], repository: { nameWithOwner: scope },
};
const issue = {
  __typename: "Issue", number: 43, title: "Issue comment heading navigation", body: "A synthetic issue for accessibility verification.",
  url: "https://" + host + "/" + scope + "/issues/43", state: "OPEN", stateReason: null,
  author: actor("author"), createdAt: time, updatedAt: time, closedAt: null,
  comments, labels: page(), assignees: page(), viewerCanUpdate: false, viewerCanClose: false,
  viewerCanReopen: false, viewerCanComment: true, locked: false, activeLockReason: null,
  reactionGroups: [], closedByPullRequestsReferences: page(), timelineItems: page(),
};
const fetchActual = globalThis.fetch;
globalThis.fetch = async (input, init) => {
  const request = new Request(input, init);
  const url = new URL(request.url);
  if (url.hostname !== host) return fetchActual(input, init);
  if (url.pathname === "/api/v3/user") return Response.json({ ...viewer, id: 123, name: null });
  if (url.pathname !== "/api/graphql") return new Response(null, { status: 404 });
  const { query } = await request.json();
  const repository = { viewerPermission: "READ", mergeCommitAllowed: false, squashMergeAllowed: false,
    rebaseMergeAllowed: false, autoMergeAllowed: false, labels: page(), assignableUsers: page(), pullRequest: pr, issue, pullRequests: page([pr]) };
  return Response.json({ data: { viewer, repository,
    search: page(query.includes("type:issue") || query.includes("is:issue") ? [issue] : [pr]), nodes: [], rateLimit: { remaining: 5000, limit: 5000, resetAt: "2099-01-01T00:00:00Z", cost: 1 } } });
};
`;

function startFixtureServer(webOrigin: string) {
  const ready = Promise.withResolvers<{ origin: string; token: string }>();
  const server = Effect.runFork(
    Effect.gen(function* () {
      yield* prepareHome(HOME);
      const port = yield* (yield* NetService.NetService).reserveLoopbackPort();
      const origin = `http://127.0.0.1:${port}`;
      const token = yield* Deferred.make<string>();
      const path = yield* Path.Path;
      const searchPath = (yield* HostProcess.Environment).PATH ?? "";
      const node = yield* HostProcess.ExecutablePath;
      const child = yield* start({
        cwd: APP_DIR,
        command: node,
        args: [
          `--import=data:text/javascript;base64,${Buffer.from(upstream).toString("base64")}`,
          "apps/server/src/bin.ts",
          "serve",
          "--host",
          "127.0.0.1",
          "--port",
          String(port),
          "--base-dir",
          HOME,
          "--dev-url",
          webOrigin,
        ],
        env: {
          PATH: `${path.join(HOME, "bin")}:${searchPath}`,
          HOME,
          GH_HOST: HOST,
          GH_ENTERPRISE_TOKEN: "scenario-only-token",
          T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0",
        },
        onLine: (line) => {
          const value = /^Token:\s*(\S+)/.exec(line)?.[1];
          return value === undefined
            ? Effect.void
            : Deferred.succeed(token, value).pipe(Effect.asVoid);
        },
      });
      const exited = child.exitCode.pipe(
        Effect.flatMap(
          (code) => new ScenarioError({ message: `Fixture server exited (${code}).` }),
        ),
      );
      ready.resolve({ origin, token: yield* Effect.raceFirst(Deferred.await(token), exited) });
      return yield* exited;
    }).pipe(Effect.scoped, Effect.provide([NodeServices.layer, NetService.layer])),
  );
  void Effect.runPromise(Fiber.join(server)).catch(ready.reject);
  return { ready: ready.promise, stop: () => Effect.runPromise(Fiber.interrupt(server)) };
}

test("Comments and reviews are destinations for heading navigation", WEB, async ({ t3, app, browser, screen }) => {
  const workspace = await t3.project("Accessibility");
  await browser.setViewport({ width: 1440, height: 1100 });
  const server = startFixtureServer(app.baseUrl ?? "");
  try {
    const { origin, token } = await server.ready;
    const repository = `${HOME}/accessibility`;
    await runPromise(run("git", ["clone", "--quiet", workspace, repository]));
    await runPromise(run("git", ["remote", "set-url", "origin", `https://${HOST}/${SCOPE}.git`], { cwd: repository }));
    const added = await runPromise(makeState(HOME).cli(["project", "add", repository]));
    const projectId = /Added project (\S+) /.exec(added.stdout)?.[1];
    if (!projectId) throw new Error("The fixture project was not added.");
    const { environmentId } = await runPromise(HttpClient.get(`${origin}/.well-known/t3/environment`).pipe(
      Effect.flatMap(HttpClientResponse.filterStatusOk),
      Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ environmentId: Schema.String }))),
      Effect.provide(FetchHttpClient.layer),
    ));
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(origin);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    await screen.getByRole("button", "More actions for Scenario").waitFor();
    const link = new URLSearchParams({ repository: SCOPE, number: "42", selectedHost: HOST,
      selectedEnvironmentId: environmentId, selectedProjectId: projectId });
    await app.open(`/pull-requests?${link}`);
    await screen.getByText("A synthetic pull request for accessibility verification.", { exact: false }).waitFor();
    const names: Record<string, string[]> = {};
    const sha = (await runPromise(run("git", ["rev-parse", "--short=10", "HEAD"], { cwd: APP_DIR }))).stdout.trim();
    const destinations: Record<string, boolean> = {};
    const read = () => browser.evaluate(() => [...document.querySelectorAll("h1,h2,h3,h4,h5,h6,[role=heading]")].filter(e => e.getBoundingClientRect().height > 0 && e.checkVisibility()).map(e => (e.textContent ?? "").trim()));
    const capture = async (label: string) => {
      await browser.mouse.move(0, 0);
      await browser.evaluate(async () => { await new Promise(r => setTimeout(r, 600)); return null; });
      let previous = await app.screenshot(`${label}-settle`);
      for (let i = 0; i < 5; i++) {
        await browser.evaluate(async () => { await new Promise(r => setTimeout(r, 500)); return null; });
        const next = await app.screenshot(i === 0 ? label : `${label}-stable-${i}`);
        if ((await readFile(previous)).equals(await readFile(next))) {
          await writeFile(`/tmp/factory-issue-39637-evidence-3/web-${sha}-${label}-tree.txt`, await screen.tree());
          return;
        }
        previous = next;
      }
      throw new Error(`Capture did not settle: ${label}`);
    };
    await screen.getByRole("button", "Timeline", { exact: true }).tap();
    const group = screen.getByRole("button", /2 comments/);
    await group.tap();
    await browser.locator("article:visible").getByText("The first conversation comment.", { exact: false }).waitFor();
    destinations.review = await screen.getByRole("heading", /bob.*approved/i).isVisible();
    destinations.comment = await screen.getByRole("heading", "alice commented", { exact: true }).isVisible();
    names.timeline = await read();
    await capture("pr-timeline-headings");
    await screen.getByRole("button", "Summary", { exact: true }).tap();
    await browser.locator("article:visible").getByText("The first conversation comment.", { exact: false }).waitFor();
    destinations.summary = await screen.getByRole("heading", /alice/).isVisible();
    names.summary = await read();
    await capture("pr-summary-headings");
    const issueLink = new URLSearchParams({ key: "43", tracker: "github", scope: SCOPE,
      selectedHost: HOST, selectedEnvironmentId: environmentId, selectedProjectId: projectId });
    await app.open(`/issues?${issueLink}`);
    await browser.locator("article:visible").getByText("The first conversation comment.", { exact: false }).waitFor();
    destinations.issue = await screen.getByRole("heading", /alice/).isVisible();
    names.issue = await read();
    await capture("issue-comment-headings");
    console.log("HEADING_INVENTORY", JSON.stringify(names));
    expect(destinations.review, JSON.stringify(destinations)).toBe(true);
    expect(destinations.comment).toBe(true);
    expect(destinations.summary).toBe(true);
    expect(destinations.issue).toBe(true);
  } finally { await server.stop(); }
});
