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

test("Claude lists managed skills and gives them precedence over personal skills", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Managed skills demo");
  const thread = await t3.thread({ project, title: "Managed skill discovery", messages: ["Ready to inspect installed skills"] });
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await readFile(settingsPath, "utf8"));
  settings.providerInstances.claudeAgent.enabled = true;
  await writeFile(settingsPath, JSON.stringify(settings));
  await t3.open(thread);
  await screen.getByRole("button", "Multi turn", { exact: false }).tap();
  await screen.getByRole("button", "Claude", { exact: true }).tap();
  await screen.getByRole("option", "Haiku 5.5", { exact: false }).tap();
  await browser.keyboard.press("Escape");
  const composer = screen.getByRole("textbox");
  await composer.fill("");
  await composer.pressSequentially("$dep");
  await screen.getByText("deploy", { exact: true }).first().waitFor({ state: "visible" });
  await app.screenshot("deploy-precedence");
  await composer.fill("");
  await composer.pressSequentially("$managed");
  await screen.getByText(/MANAGED-ONLY skill installed by administrator|No skills found/).waitFor({ state: "visible" });
  await app.screenshot("managed-skill-menu");
  await expect(screen.getByText("MANAGED-ONLY skill installed by administrator", { exact: true })).toBeVisible();
  await screen.getByText("managed-only", { exact: true }).tap();
  await app.screenshot("managed-skill-chip");
  await expect(composer).toContainText("managed-only");
  await composer.fill("");
  await composer.pressSequentially("$dep");
  await expect(screen.getByText("MANAGED deploy skill (org-enforced copy)", { exact: true })).toBeVisible();
  await expect(screen.getByText("PERSONAL deploy skill (user copy)", { exact: true })).not.toBeVisible();
});
