import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { mcpToolSession } from "../../apps/server/src/mcp/AcpMcpStdioBridge.ts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

// Uses only this run's fresh home. No writes to the forge.
const cli = (...args: string[]) => execFileSync(process.execPath,
  ["apps/server/src/bin.ts", ...args, "--base-dir", T3_HOME],
  { cwd: APP_DIR, encoding: "utf8", env: { ...process.env, T3CODE_DEV_SEED: "0" } }).trim();

test("Watching a PR with completed checks does not wake the thread on its first read", WEB,
  async ({ t3, app, screen, browser }) => {
    const project = await t3.project("watch-demo");
    await t3.thread({ project, title: "Watch completed checks", messages: ["Watch the pull request after its checks have completed."] });
    const [thread] = JSON.parse(cli("thread", "list", "--project", project, "--json"));
    const token = cli("auth", "session", "issue", "--subject", "mcp-client", "--token-only");
    const { origin } = JSON.parse(readFileSync(`${T3_HOME}/userdata/server-runtime.json`, "utf8"));
    await t3.open();
    await browser.locator(`[data-thread-item$=":${thread.threadId}"]`).tap();
    await Effect.runPromise(Effect.scoped(Effect.gen(function* () {
      const session = yield* mcpToolSession({ endpoint: `${origin}/mcp`, authorization: `Bearer ${token}`, clientName: "watch-proof" });
      const result = yield* session.call("watch_pull_request", { threadId: thread.threadId, url: "https://github.com/pingdotgg/t3code/pull/23522" });
      if ((result as { isError?: boolean }).isError) throw new Error(JSON.stringify(result));
    })));
    await app.screenshot("watch-started");
    // The real watcher sweeps every two minutes. Leave the PR unchanged through its first read.
    await new Promise((resolve) => setTimeout(resolve, 135_000));
    await app.screenshot("initial-background-read");
    await expect(screen.getByText("checks passed", { exact: false }).first()).toBeHidden();
  });
