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

test("Failed registry install retains a short stderr tail and its final diagnostic", WEB, async ({ t3, app, screen, browser }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  await t3.project("demo");
  const shim = `${T3_HOME}/bin/npm`;
  await writeFile(shim, `#!/usr/bin/python3
import os, sys
args = sys.argv[1:]
if args == ['root', '--global']:
 print(os.environ.get('npm_config_prefix', '/tmp/synthetic-npm') + '/lib/node_modules')
 sys.exit(0)
if args == ['prefix', '--global']:
 print(os.environ.get('npm_config_prefix', '/tmp/synthetic-npm'))
 sys.exit(0)
if args[:2] == ['install', '--global']:
 sys.stderr.write('npm notice resolving example dependency\\n' * 40000)
 sys.stderr.write('E_FINAL_DIAGNOSTIC_XYZ: synthetic installation failed\\n')
 sys.exit(1)
sys.exit(1)
`);
  await chmod(shim, 0o755);
  await t3.open("/settings/providers");
  await screen.getByRole("button", "Add provider", { exact: true }).first().tap();
  await screen.getByRole("button", "Show more", { exact: true }).tap();
  // Redact only the executable's absolute path from public captures and video.
  await browser.evaluate(() => {
    new MutationObserver(() => {
      for (const el of document.querySelectorAll('[role="status"] *')) {
        if (el.children.length === 0 && el.textContent?.includes("ACP Registry install command") && !el.textContent.includes("command 'npm'")) {
          el.textContent = el.textContent.replace(/command '[^']*'/, "command 'npm'");
        }
      }
    }).observe(document.body, { childList: true, subtree: true, characterData: true });
    return null;
  });
  await screen.getByRole("button", "Add Gemini CLI", { exact: true }).tap();
  await screen.getByText(/ACP Registry install command/).waitFor({ state: "visible", timeout: 60000 });
  await app.screenshot("failed-install");
  await browser.evaluate(() => {
    const error = [...document.querySelectorAll('[role="status"]')].find(el => el.textContent?.includes('ACP Registry install command'));
    error?.scrollIntoView({ block: "end", behavior: "instant" });
    return null;
  });
  await app.screenshot("stderr-tail");
  const error = screen.getByText(/ACP Registry install command/);
  await expect(error).toContainText("exited with code 1");
  await expect(error).toContainText("E_FINAL_DIAGNOSTIC_XYZ");
  const text = await browser.evaluate(() => [...document.querySelectorAll('[role="status"]')].map(el => el.textContent ?? '').find(text => text.includes('ACP Registry install command')) ?? '');
  expect(text.length).toBeLessThan(1500);
});
