import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { writeFile, readFile } from "node:fs/promises";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("GitHub remote status survives an invalid secondary SCP host", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("github-remote-proof");
  for (const args of [
    ["checkout", "-b", "feature/x"],
    ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"],
    ["remote", "add", "backup", "git@nas.08:team/repo.git"],
    ["remote", "add", "ipv6", "git@[2001:db8::1]:team/repo.git"],
  ]) await runPromise(run("git", args, { cwd: project }));
  const thread = await t3.thread({ project, title: "GitHub secondary remote proof", messages: ["Show the repository status"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer").waitFor();
  const result = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    return yield* client["vcs.refreshStatus"]({ cwd: project }).pipe(
      Effect.matchCause({
        onFailure: (cause) => ({ success: false, detail: String(cause) }),
        onSuccess: (status) => ({ success: true, status }),
      }),
    );
  }).pipe(Effect.scoped));
  const publicResult = JSON.parse(JSON.stringify(result).replaceAll(project, "<synthetic repository>"));
  console.log("REMOTE_STATUS_RESULT", JSON.stringify(publicResult));
  const transcript = [
    "GitHub remote status / PR lookup: live server RPC",
    "Branch: feature/x",
    "origin: https://github.com/pingdotgg/t3code.git",
    "backup: git@nas.08:team/repo.git",
    "ipv6:   git@[2001:db8::1]:team/repo.git",
    "",
    "success: " + result.success,
    ...("detail" in result ? [result.detail] : [
      "provider: " + result.status.sourceControlProvider?.kind,
      "provider URL: " + result.status.sourceControlProvider?.baseUrl,
      "refName: " + result.status.refName,
      "PR lookup completed: " + JSON.stringify(result.status.pr),
    ]),
  ].join("\n");
  await writeFile(`${project}/remote-status-proof.txt`, transcript);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  await terminal.waitFor();
  // Wait for the real shell to accept input before clearing its private prompt.
  for (let attempt = 0; attempt < 10; attempt++) {
    await terminal.focus();
    await browser.keyboard.type("export PS1='$ '; clear; cat remote-status-proof.txt; echo ready > proof-ready");
    await browser.keyboard.press("Enter");
    await new Promise((resolve) => setTimeout(resolve, 500));
    if (await readFile(`${project}/proof-ready`, "utf8").catch(() => "") === "ready\n") break;
  }
  await new Promise((resolve) => setTimeout(resolve, 1000));
  await app.screenshot("github-remote-status");
  expect(result.success).toBe(true);
});
