import { readFile, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import { parseEnv } from "node:util";
import { ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const title = "[pr-44693-proof] explicit HTTPS default port";

test("A bound Linear issue with port 443 opens beside the chat", WEB, async ({ t3, app, screen, browser }) => {
  const config = parseEnv(await readFile(`${homedir()}/.config/linear-test.env`, "utf8"));
  const graphql = async (query: string, variables: Record<string, unknown> = {}) => {
    const response = await fetch("https://api.linear.app/graphql", {
      method: "POST", headers: { Authorization: config.LINEAR_API_KEY!, "Content-Type": "application/json" },
      body: JSON.stringify({ query, variables }),
    });
    const result = await response.json();
    if (result.errors) throw new Error(JSON.stringify(result.errors));
    return result.data;
  };
  const created = await graphql(`mutation($input: IssueCreateInput!) { issueCreate(input: $input) { issue { id identifier url } } }`, {
    input: { teamId: config.LINEAR_TEST_TEAM_ID, title, description: "Synthetic issue for the default HTTPS port proof." },
  });
  const issue = created.issueCreate.issue;
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await readFile(fixture, "utf8");
  const withPort = issue.url.replace("https://linear.app/", "https://linear.app:443/");
  const turns = [
    `[${issue.identifier} with port](${withPort})`,
    `[${issue.identifier} no port](${issue.url})`,
  ].flatMap((text) => [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "replay", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ]);
  try {
    await writeFile(fixture, turns.map((entry) => JSON.stringify(entry)).join("\n") + "\n");
    const project = await t3.project("server");
    const thread = await t3.thread({ project, title: "Linear HTTPS port proof", messages: ["Show the issue link with port 443"], model: "showcase" });
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      const projection = yield* client["orchestration.getThreadProjection"]({ threadId: ThreadId.make(thread.threadId) });
      yield* client["issueTrackers.connect"]({ tracker: "linear", token: config.LINEAR_API_KEY! });
      yield* client["issueTrackers.bindProject"]({ projectId: projection.thread.projectId, binding: { tracker: "linear", scope: config.LINEAR_TEST_TEAM_KEY! } });
    }).pipe(Effect.scoped));
    await t3.open(thread);
    const panel = screen.getByRole("heading", title, { exact: true });
    const portLink = screen.getByRole("link", `${issue.identifier} with port`, { exact: true });
    await browser.locator(`a[data-slot="preview-card-trigger"][href="${withPort}"]`).waitFor({ timeout: 5000 }).catch(() => undefined);
    await portLink.tap();
    const firstOpened = await panel.waitFor({ timeout: 5000 }).then(() => true, () => false);
    await app.screenshot("443-first-click");
    if (firstOpened) await screen.getByRole("button", `Close ${issue.identifier}`, { exact: true }).tap();
    await runPromise(makeState(T3_HOME).cli(["thread", "send", thread.threadId, "Show the same issue without a port", "--wait", "--json"]));
    await browser.locator(`a[data-slot="preview-card-trigger"][href="${issue.url}"]`).waitFor();
    await screen.getByRole("link", `${issue.identifier} no port`, { exact: true }).tap();
    await panel.waitFor();
    await app.screenshot("no-port-control");
    await screen.getByRole("button", `Close ${issue.identifier}`, { exact: true }).tap();
    await portLink.tap();
    const reopened = await panel.waitFor({ timeout: 5000 }).then(() => true, () => false);
    await app.screenshot("443-click-after-bindings-loaded");
    expect({ firstOpened, reopened }).toEqual({ firstOpened: true, reopened: true });
  } finally {
    await writeFile(fixture, original);
    await graphql(`mutation($id: String!) { issueArchive(id: $id) { success } }`, { id: issue.id });
  }
});
