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

const prefix = "/tmp/factory-pr-25208-a1795412013-evidence-1/macports";
test("MacPorts registry failure keeps Claude updates manual", WEB, async ({ t3, app, browser, screen }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  await t3.project("demo");
  await mkdir(`${prefix}/bin`, { recursive: true });
  await mkdir(`${prefix}/lib/node_modules/@anthropic-ai/claude-code`, { recursive: true });
  const cli = `${prefix}/lib/node_modules/@anthropic-ai/claude-code/cli.js`;
  await writeFile(cli, '#!/bin/sh\nif [ "$1" = "--version" ]; then echo "1.0.0 (Claude Code)"; exit 0; fi\nif [ "$1" = "auth" ]; then echo \'{"loggedIn":false}\'; exit 0; fi\nexit 1\n');
  await chmod(cli, 0o755);
  await symlink(cli, `${prefix}/bin/claude`).catch(e => { if (e.code !== "EEXIST") throw e; });
  await writeFile(`${prefix}/bin/port`, '#!/bin/sh\nprintf "%s\\n" "$*" >> "$(dirname "$0")/../port-calls.log"\nexit 1\n');
  await chmod(`${prefix}/bin/port`, 0o755);
  await t3.open("/settings/providers?instanceId=claudeAgent");
  await screen.getByRole("textbox", "Binary path").fill(`${prefix}/bin/claude`);
  await browser.keyboard.press("Tab");
  const enable = screen.getByRole("switch", "Enable Claude", { exact: true });
  await enable.tap();
  await screen.getByRole("button", /^Refresh provider status/).last().tap();
  await browser.locator('button[aria-busy="false"]').waitFor({ timeout: 60000 });
  const details = screen.getByRole("button", /view details/).last();
  await details.waitFor({ state: "visible", timeout: 60000 });
  await details.tap();
  await screen.getByRole("dialog").last().waitFor({ state: "visible" });
  await browser.evaluate(() => { for (const a of document.getAnimations()) if (Number.isFinite(a.effect?.getComputedTiming().endTime)) a.finish(); return null; });
  await app.screenshot("macports-update-advisory");
  await expect(screen.getByRole("button", "Update now", { exact: true })).not.toBeVisible();
  await expect(screen.getByRole("button", "Update all", { exact: true })).not.toBeVisible();
});
