import { execFileSync } from "node:child_process";
import { writeFileSync } from "node:fs";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";
const config = (name: string) => JSON.stringify({ provider: { uni: { npm: "@ai-sdk/openai-compatible", name: "uni", options: { baseURL: "http://127.0.0.1:9/v1", apiKey: "synthetic" }, models: { [name]: { name, limit: { context: 32000, output: 4000 } } } } } });
test("Project catalogs follow existing threads and their worktrees", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Project A", { "opencode.jsonc": config("medium-gpt") });
  const other = await t3.project("Project B");
  await t3.thread({ project, title: "Existing project thread", messages: ["Hello"], model: "showcase" });
  await t3.thread({ project: other, title: "Other project thread", messages: ["Hello"], model: "showcase" });
  await t3.thread({ project, title: "Existing worktree thread", messages: ["Hello"], model: "showcase", worktree: "main" });
  const worktree = execFileSync("git", ["worktree", "list", "--porcelain"], { cwd: project, encoding: "utf8" }).split("\n").filter(line => line.startsWith("worktree ")).map(line => line.slice(9)).find(path => path !== project)!;
  writeFileSync(`${worktree}/opencode.jsonc`, config("medium-worktree"));
  await t3.open();
  const picker = async (title: string, query: string) => {
    await screen.getByRole("button", `${title},`, { exact: false }).tap();
    await screen.getByRole("button", "showcase", { exact: false }).tap();
    await screen.getByRole("button", "OpenCode", { exact: true }).tap();
    await screen.getByPlaceholder("Search models...").fill(query);
  };
  await picker("Existing worktree thread", "medium-worktree");
  const worktreeOption = screen.getByRole("option", "medium-worktree", { exact: false });
  await worktreeOption.waitFor({ state: "visible", timeout: 15000 }).catch(() => {});
  const foundInWorktree = await worktreeOption.isVisible();
  await app.screenshot("worktree-catalog");
  await browser.keyboard.press("Escape");
  await picker("Other project thread", "medium-gpt");
  await app.screenshot("project-b-isolation");
  await expect(screen.getByRole("option", "medium-gpt", { exact: false })).toBeHidden();
  await browser.keyboard.press("Escape");
  await picker("Existing project thread", "medium-gpt");
  await app.screenshot("project-a-search-start");
  await screen.getByRole("option", "medium-gpt", { exact: false }).waitFor({ state: "visible", timeout: 15000 }).catch(() => {});
  await app.screenshot("project-a-catalog");
  await expect(screen.getByRole("option", "medium-gpt", { exact: false })).toBeVisible();
  await expect(foundInWorktree).toBe(true);
});
