import { expect } from "e2e";
import { readFile, writeFile } from "node:fs/promises";
import * as Effect from "effect/Effect";
import { test, WEB, makeState, runPromise } from "./t3.ts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { mcpToolSession } from "../../apps/server/src/mcp/AcpMcpStdioBridge.ts";

async function transcript(threadId: string, workspaceRoot: string) {
  const { cli } = makeState(T3_HOME);
  const { origin } = JSON.parse(await readFile(`${T3_HOME}/userdata/server-runtime.json`, "utf8"));
  const owner = (await runPromise(cli(["auth", "session", "issue", "--token-only"]))).stdout.trim();
  const snapshot = await (await fetch(`${origin}/api/projects`, { headers: { authorization: `Bearer ${owner}` } })).json();
  const project = snapshot.projects.find((entry: { workspaceRoot: string }) => entry.workspaceRoot === workspaceRoot);
  const token = (await runPromise(cli(["auth", "session", "issue", "--subject", "mcp-client", "--token-only"]))).stdout.trim();
  const calls = await runPromise(Effect.gen(function* () {
    const session = yield* mcpToolSession({ endpoint: `${origin}/mcp`, authorization: `Bearer ${token}`, clientName: "forgejo-proof" });
    const url = "http://git.example.test:18871/scenario/demo/issues/1";
    const keyRead = yield* session.call("read_issue", { projectId: project.id, key: "1" });
    const urlRead = yield* session.call("read_issue", { url });
    const urlLink = yield* session.call("link_issue", { threadId, url });
    const links = yield* session.call("list_thread_issues", { threadId });
    return { keyRead, urlRead, urlLink, links };
  }).pipe(Effect.scoped));
  const sha = (await runPromise(run("git", ["rev-parse", "HEAD"], { cwd: APP_DIR }))).stdout.trim();
  await writeFile(`${process.env.PROOF_OUTPUT_DIR}/${sha}-mcp.json`, JSON.stringify({ sha, host: "git.example.test:18871", provider: project.repositoryIdentity?.provider, calls }, null, 2));
}

test("A configured self-hosted Forgejo issue link opens beside its thread", WEB, async ({ t3, app, screen, browser }) => {
  await browser.setViewport({ width: 1440, height: 1000 });
  await browser.emulateMedia({ reducedMotion: "reduce", colorScheme: "light" });
  const project = await t3.project("Forgejo demo", {
    ".git/config": '[remote "origin"]\n  url = http://git.example.test:18871/scenario/demo.git\n  fetch = +refs/heads/*:refs/remotes/origin/*\n',
    "README.md": "Synthetic Forgejo issue-link reproduction.\n",
  });
  const thread = await t3.thread({
    project,
    title: "Open a self-hosted Forgejo issue",
    messages: ["Please inspect this issue: http://git.example.test:18871/scenario/demo/issues/1"],
  });
  await t3.open(thread);
  await screen.getByRole("button", /^Agent Please inspect this issue:/).tap();
  const link = screen.getByRole("link", "http://git.example.test:18871/scenario/demo/issues/1");
  await link.tap();
  try {
    await expect(screen.getByText("Self-hosted issue opens inside the thread", { exact: true })).toBeVisible({ timeout: 20000 });
  } finally {
    await browser.mouse.move(30, 600);
    await new Promise((resolve) => setTimeout(resolve, 700));
    let previous = await app.screenshot("settled-check-0");
    let stable = false;
    for (let frame = 1; frame <= 10; frame++) {
      await new Promise((resolve) => setTimeout(resolve, 500));
      const current = await app.screenshot(`settled-check-${frame}`);
      if ((await readFile(previous)).equals(await readFile(current))) { stable = true; break; }
      previous = current;
    }
    if (!stable) throw new Error("Capture has not settled");
    await app.screenshot("issue-link-clicked");
    await transcript(thread.threadId, project);
  }
});
