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

test("Claude launch-argument plugin skills appear in both composer menus", WEB, async ({ t3, app, screen, browser }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  await t3.project("login-demo", {
    "acme/.claude-plugin/plugin.json": '{"name":"acme"}',
    "acme/skills/qa/SKILL.md": "---\nname: qa\ndescription: Check the login flow\n---\nCheck the login flow and report findings.\n",
  });
  const plugin = path.join(T3_HOME, "acme");
  await fs.mkdir(path.join(plugin, ".claude-plugin"), { recursive: true });
  await fs.mkdir(path.join(plugin, "skills/qa"), { recursive: true });
  await fs.writeFile(path.join(plugin, ".claude-plugin/plugin.json"), '{"name":"acme"}');
  await fs.writeFile(path.join(plugin, "skills/qa/SKILL.md"), "---\nname: qa\ndescription: Check the login flow\n---\nCheck the login flow and report findings.\n");
  const observer = path.join(T3_HOME, "bin/claude-observer");
  await fs.writeFile(observer, `#!/usr/bin/python3
import sys, subprocess, json, threading, os
if "--input-format" not in sys.argv:
    os.execv("/usr/local/bin/claude", ["claude", *sys.argv[1:]])
child = subprocess.Popen(["/usr/local/bin/claude", *sys.argv[1:]], stdin=subprocess.PIPE)
def forward():
    for line in sys.stdin.buffer:
        try:
            frame = json.loads(line)
            if frame.get("type") == "user":
                content = frame.get("message", {}).get("content", [])
                if isinstance(content, str): content = [{"type": "text", "text": content}]
                for block in content:
                    text = block.get("text", "")
                    if "acme:qa" in text:
                        with open(${JSON.stringify(path.join(T3_HOME, "dispatch.json"))}, "w") as output:
                            json.dump({"text": text}, output)
        except Exception: pass
        child.stdin.write(line)
        child.stdin.flush()
threading.Thread(target=forward, daemon=True).start()
sys.exit(child.wait())
`, { mode: 0o755 });
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.claudeAgent = { driver: "claudeAgent", enabled: true, config: { binaryPath: observer, launchArgs: `--plugin-dir ${plugin}` } };
  settings.defaultModelSelection = { instanceId: "claudeAgent", model: "claude-haiku-4-5" };
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  await t3.open();
  await screen.getByRole("textbox").fill("$acme");
  await screen.getByText(/acme:qa|No skills found/).first().waitFor({ state: "visible" });
  await app.screenshot("dollar-menu");
  const dollarHasSkill = await screen.getByText("acme:qa", { exact: false }).first().isVisible();
  await screen.getByRole("textbox").fill("/acme");
  await screen.getByText(/acme:qa|No matching command/).first().waitFor({ state: "visible" });
  await app.screenshot("slash-menu");
  const slashHasSkill = await screen.getByText("acme:qa", { exact: false }).first().isVisible();
  await screen.getByRole("textbox").fill("$acme:qa check the login flow");
  await screen.getByRole("textbox").press("Enter");
  let observedPrompt: string | null = null;
  await expect.poll(async () => {
    try {
      observedPrompt = JSON.parse(await fs.readFile(path.join(T3_HOME, "dispatch.json"), "utf8")).text;
      return observedPrompt !== null;
    } catch { return false; }
  }, { timeout: 60_000 }).toBe(true);
  const sha = execFileSync("git", ["rev-parse", "HEAD"], { cwd: APP_DIR, encoding: "utf8" }).trim();
  await fs.writeFile(new URL(`./claude-plugin-dir-dispatch-${sha.slice(0, 10)}.json`, import.meta.url), JSON.stringify({ sha, dollarHasSkill, slashHasSkill, observedPrompt }, null, 2));
  await expect(observedPrompt).toBe("/acme:qa check the login flow");
  await expect(dollarHasSkill).toBe(true);
  await expect(slashHasSkill).toBe(true);
});
