import { expect } from "e2e";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { createHash } from "node:crypto";
import { join } from "node:path";
import { test, WEB, makeState, runPromise } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";

test("Antigravity profile plugin skills appear while disabled plugins stay hidden", WEB, async ({t3, app, screen, browser}) => {
  const skill = (name: string) => `---\nname: ${name}\ndescription: Synthetic evidence skill.\n---\nReply OK.\n`;
  const project = await t3.project("Plugin skills demo", {".agents/skills/factory-control/SKILL.md": skill("factory-control")});
  const profile = join(T3_HOME,"userdata/providers/antigravity",createHash("sha256").update("antigravity").digest("hex"));
  for (const [plugin, names] of [["factory-demo",["factory-plugin-alpha","factory-plugin-beta"]],["factory-disabled",["factory-disabled-skill"]]] as const) {
    const root = join(profile,"config/plugins",plugin);
    await mkdir(root,{recursive:true});
    await writeFile(join(root,"plugin.json"),JSON.stringify({name:plugin,version:"1.0.0",description:"Synthetic plugin evidence"}));
    for (const name of names) {
      const dir = join(root,"skills",name); await mkdir(dir,{recursive:true}); await writeFile(join(dir,"SKILL.md"),skill(name));
    }
  }
  await mkdir(join(profile,"config"),{recursive:true});
  await writeFile(join(profile,"config/config.json"),JSON.stringify({plugins:{"factory-disabled":{enabled:false}}}));
  const settingsPath=join(T3_HOME,"userdata/settings.json");
  const settings=JSON.parse(await readFile(settingsPath,"utf8"));
  settings.providerInstances.antigravity={driver:"antigravity",enabled:true,config:{authMethod:"gemini-api-key",apiKey:"synthetic-test-key"}};
  await writeFile(settingsPath,JSON.stringify(settings));
  await t3.open("/settings/providers");
  await screen.getByRole("button", "Refresh provider status", {exact:false}).tap();
  const {cli}=makeState(T3_HOME);
  const launched=await runPromise(cli(["thread","start",project,"Reply with the single word OK.","--title","Antigravity plugin skills","--provider","antigravity","--model","gemini-3.8-flash","--json","--wait"]));
  const thread=JSON.parse(launched.stdout);
  await t3.open({threadId:thread.threadId});
  const diagnostic = await browser.evaluate((cwd) => new Promise<string>((resolve, reject) => {
    const ws = new WebSocket(location.origin.replace("http", "ws")+"/ws?orchestrationProtocol=2");
    ws.onopen=()=>ws.send(JSON.stringify({_tag:"Request", id:"proof-refresh", tag:"server.refreshProviders", payload:{instanceId:"antigravity",cwd,fresh:true},headers:[]}));
    ws.onmessage=(event)=>{const parsed=JSON.parse(String(event.data)); const data=(Array.isArray(parsed)?parsed:[parsed]).find((entry)=>entry.requestId==="proof-refresh");if(data?.requestId==="proof-refresh"){resolve(JSON.stringify(data));ws.close();}};
    ws.onerror=()=>reject(new Error("refresh websocket failed"));
  }),project);
  await writeFile("/tmp/factory-issue-38925-evidence-1/refresh-diagnostic.json",diagnostic);
  await t3.open({threadId:thread.threadId});
  await screen.getByRole("textbox").fill("$factory");
  await screen.getByText("factory-control",{exact:true}).waitFor({state:"visible",timeout:30000});
  await app.screenshot("plugin-skills");
  await expect(screen.getByText("factory-plugin-alpha",{exact:true})).toBeVisible();
  await expect(screen.getByText("factory-plugin-beta",{exact:true})).toBeVisible();
  await expect(screen.getByText("factory-disabled-skill",{exact:true})).toBeHidden();
});
