import * as fs from "node:fs/promises";
import * as Effect from "effect/Effect";
import { CommandId, ThreadId, ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Uppercase root SKILL.MD leaves Antigravity child skills visible", WEB, async ({t3, app, screen}) => {
  const child = "---\nname: review\ndescription: Review the code\n---\nReview the code.\n";
  const stray = "---\nname: stray\ndescription: Stray root skill\n---\nStray.\n";
  const fixtures = [
    ["proj-control", ".agents", false],
    ["proj-agents", ".agents", true],
    ["proj-agent", ".agent", true],
  ] as const;
  const projects = [];
  for (const [title, root, hasStray] of fixtures) {
    projects.push({title, project: await t3.project(title, {
      [`${root}/skills/review/SKILL.md`]: child,
      ...(hasStray ? {[`${root}/skills/SKILL.MD`]: stray} : {}),
    })});
  }
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.antigravity = {driver:"antigravity",enabled:true,config:{authMethod:"gemini-api-key",apiKey:"scenario-placeholder"}};
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  const threads = [];
  for (const {title, project} of projects) {
    const thread = await t3.thread({project, title, messages:["Hello"]});
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["orchestration.dispatchCommand"]({
        type:"thread.model-selection.set", commandId:CommandId.make(crypto.randomUUID()),
        threadId:ThreadId.make(thread.threadId),
        modelSelection:{instanceId:ProviderInstanceId.make("antigravity"),model:"gemini-3.8-flash",options:[]},
      });
      yield* client["server.refreshProviders"]({instanceId:ProviderInstanceId.make("antigravity"),cwd:project,fresh:true});
    }).pipe(Effect.scoped));
    threads.push({title, ...thread});
  }
  const visible = [];
  for (const thread of threads) {
    await t3.open(thread);
    await screen.getByText("Syncing messages...", {exact:true}).waitFor({state:"hidden"});
    const composer = screen.getByRole("textbox");
    await composer.pressSequentially("$");
    await screen.getByText(/Review the code|No skills found/).first().waitFor();
    await screen.getByText("Syncing messages...", {exact:true}).waitFor({state:"hidden"});
    await app.screenshot(thread.title);
    visible.push(await screen.getByText("Review the code", {exact:true}).isVisible());
  }
  await expect(visible).toEqual([true,true,true]);
});
