import { expect } from "e2e";
import * as fs from "node:fs/promises";
import { watch } from "node:fs";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Claude sign in becomes available after installation with the terminal still open", WEB, async ({ t3, app, screen, browser }) => {
  const installHome = await fs.mkdtemp("/tmp/factory-pr-41267-evidence-1/install-");
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.claudeAgent = { driver: "claudeAgent", enabled: true, config: { homePath: `${installHome}/.claude`, binaryPath: `${installHome}/.local/bin/claude` } };
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  await t3.project("Onboarding demo");
  await t3.open("/welcome");
  const install = screen.getByRole("button", "Install: Claude", { exact: true });
  if (!(await browser.evaluate(() => !!document.querySelector('button[aria-label="Install: Claude"]')))) {
    await screen.getByRole("button", "Add more agents", { exact: false }).tap();
  }
  await install.tap();
  await screen.getByRole("textbox", "Terminal input", { exact: true }).focus();
  await browser.keyboard.press("Control+u");
  await browser.keyboard.type(`export HOME='${installHome}'; export PS1='demo $ '; cd "$HOME"; clear; curl -fsSL https://claude.ai/install.sh | bash`);
  await browser.keyboard.press("Enter");
  const logs = `${T3_HOME}/userdata/logs/terminals`;
  await new Promise<void>((resolve, reject) => {
    const watcher = watch(logs, () => { void check(); });
    watcher.unref();
    const check = async () => {
      try {
        const files = await fs.readdir(logs);
        const contents = await Promise.all(files.map(file => fs.readFile(`${logs}/${file}`, "utf8")));
        if (contents.some(content => content.includes("Setting up Claude Code..."))) { watcher.close(); resolve(); }
      } catch (error) { watcher.close(); reject(error); }
    };
    void check();
  });
  await expect(install).toBeDisabled();
  await app.screenshot("installation-running");
  const signIn = screen.getByRole("button", "Sign in: Claude", { exact: true });
  await signIn.waitFor({ state: "visible", timeout: 240000 });
  await app.screenshot("installed-terminal-open");
  await expect(signIn).toBeEnabled({ timeout: 20000 });
  await signIn.tap();
  await browser.locator("[data-thread-terminal-drawer] canvas").waitFor({state: "visible"});
  await screen.getByText("Review the command, then press Enter to run it.", { exact: true }).waitFor({ state: "visible" });
  await app.screenshot("fresh-sign-in-terminal");
});
