import { execFileSync } from "node:child_process";
import { copyFile, unlink, writeFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { CommandId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const scratch = process.env.GH_CONFIG_DIR!.replace(/\/gh$/, "");
test("A stopped PR watch explains server CLI authentication", { ...WEB, timeout: 1_900_000 }, async ({ t3, app, screen, browser }) => {
  await copyFile(`${scratch}/hosts-backup.yml`, `${scratch}/gh/hosts.yml`);
  const project = await t3.project("watch-demo");
  const thread = await t3.thread({ project, title: "Watch host authentication", messages: ["Watch the pull request and report host setup problems."] });
  await browser.setViewport({ width: 1440, height: 1000 });
  await t3.open(thread);
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["orchestration.dispatchCommand"]({
      type: "thread.pull-request.watch", commandId: CommandId.make(randomUUID()), threadId: ThreadId.make(thread.threadId),
      host: "github.com", repository: "pingdotgg/t3code", number: 35145, watching: true, until: "merged",
      link: { url: "https://github.com/pingdotgg/t3code/pull/35145", source: "agent" }
    });
  }).pipe(Effect.scoped));
  await screen.getByText(/Watching pull request #35145/).first().waitFor({ timeout: 120_000 });
  await unlink(`${scratch}/gh/hosts.yml`);
  const stopped = screen.getByText(/#35145: stopped watching/).first();
  await stopped.waitFor({ timeout: 1_700_000 });
  await stopped.tap();
  await screen.getByText("second fixture turn complete", { exact: false }).first().waitFor({ timeout: 60_000 });
  await app.screenshot("watch-stopped");
  const sha = execFileSync("git", ["rev-parse", "HEAD"], { cwd: APP_DIR, encoding: "utf8" }).trim();
  const messages = execFileSync("sqlite3", ["-readonly", `${T3_HOME}/userdata/statev2.sqlite`, "select json_object('summary',json_extract(payload_json,'$.notification.summary'),'text',json_extract(payload_json,'$.text')) from orchestration_v2_projection_messages where json_extract(payload_json,'$.notification.source.kind')='monitor';"], { encoding: "utf8" });
  await writeFile(`${scratch}/runtime-${sha}.json`, messages);

  await expect(screen.getByText("#35145: stopped watching, host not set up on the server", { exact: true })).toBeVisible();
});
