import * as fs from "node:fs/promises";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB, environmentId, runPromise, makeState } from "./t3.ts";

test("Projects settings opens the selected environment's expanded history importer", WEB, async ({t3, app, screen, browser}) => {
  const project = `${process.env.PI_CODING_AGENT_SESSION_DIR}/../history/demo`;
  await fs.mkdir(project, {recursive:true});
  await runPromise(makeState(T3_HOME).cli(["project", "add", project]));
  const thread = await t3.thread({project, title: "Project import proof", messages: ["go"]});
  const settingsFile = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await fs.readFile(settingsFile, "utf8"));
  settings.providerInstances.pi.enabled = true;
  await fs.writeFile(settingsFile, JSON.stringify(settings));
  await t3.open(thread);
  const id = await runPromise(environmentId(app.baseUrl!));
  await t3.open(`/settings/projects?machine=${encodeURIComponent(id)}`);
  await screen.getByText("Choose a project to manage its name, icon, checkouts and actions.", {exact:true}).waitFor();
  await app.screenshot("projects-settings");
  await expect(screen.getByText("Import projects and their threads", {exact:true})).toBeVisible();
  await screen.getByRole("link", "Open", {exact:true}).tap();
  await screen.getByRole("button", "Select none", {exact:true}).waitFor();
  await app.screenshot("expanded-project-importer");
  await expect(screen.getByRole("button", "Select all", {exact:true})).toBeVisible();
  await expect(screen.getByRole("button", "Select none", {exact:true})).toBeVisible();
  await expect(screen.getByRole("checkbox", /atlas/)).toBeVisible();
  await expect(screen.getByRole("checkbox", /beacon/)).toBeVisible();
  expect(await browser.evaluate("location.hash")).toBe(`#projects:${id}`);
  await t3.open("/welcome#projects:unknown-environment-id");
  await screen.getByText("What should we work on?", {exact:true}).waitFor();
  await app.screenshot("unknown-environment");
  await expect(screen.getByRole("button", "Select none", {exact:true})).not.toBeVisible();
  await expect(screen.getByRole("checkbox", /atlas/)).not.toBeVisible();
});
