import * as fs from "node:fs/promises";
import * as path from "node:path";
import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("A silent Antigravity initialize fails visibly instead of queuing forever", { ...WEB, timeout: 600_000 }, async ({ t3, app, screen }) => {
  const project = await t3.project("startup-demo");
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const original = await fs.readFile(settingsPath, "utf8");
  const settings = JSON.parse(original);
  const binary = path.join(T3_HOME, "bin", "agy");
  const realAgy = execFileSync("which", ["agy"], { encoding: "utf8" }).trim();
  await fs.writeFile(binary, `#!/bin/sh\nif [ "$1" = "acp" ]; then exec sleep 3600; fi\nexec '${realAgy.replaceAll("'", "'\\''")}' "$@"\n`, { mode: 0o755 });
  settings.providerInstances.antigravity = {
    driver: "antigravity", enabled: true,
    config: { binaryPath: binary, authMethod: "gemini-api-key", apiKey: "scenario-placeholder" },
  };
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  try {
    const { cli } = makeState(T3_HOME);
    let threadId: string | undefined;
    for (let attempt = 0; attempt < 8 && threadId === undefined; attempt++) {
      const started = await runPromise(cli(["thread", "start", project, "Say hello", "--title", "Silent provider startup", "--provider", "antigravity", "--model", "gemini-4-neon", "--json"], [0, 1]));
      if (started.stdout.includes("threadId")) threadId = JSON.parse(started.stdout).threadId;
    }
    if (!threadId) throw new Error("Could not start Antigravity thread");
    await t3.open({ threadId });
    await screen.getByText("Working for", { exact: false }).first().waitFor({ timeout: 60_000 });
    await screen.getByRole("textbox").fill("First follow-up");
    await screen.getByRole("textbox").press("Enter");
    await screen.getByRole("textbox").fill("Second follow-up");
    await screen.getByRole("textbox").press("Enter");
    await app.screenshot("follow-ups-queued");
    try {
      await expect(screen.getByRole("alert").filter({ hasText: "Failed to open antigravity provider session" })).toBeVisible({ timeout: 470_000 });
      await expect(screen.getByRole("button", "Stop generation")).toBeHidden();
    } finally {
      await app.screenshot("startup-outcome");
    }
  } finally {
    await fs.writeFile(settingsPath, original);
  }
});
