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

test("Typed absolute dot segments use the resolved title and reopen an existing project", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Starting project", messages: ["Hello"], model: "default" });
  const folder = "/tmp/factory-pr-46618-evidence-3/home/me/code/app";
  await fs.mkdir(folder, { recursive: true });
  await t3.open(thread);
  await screen.getByTestId("composer-editor").waitFor();
  const palette = screen.getByRole("dialog", "Command palette");
  const settle = async () => browser.evaluate("async () => { await Promise.all(document.getAnimations().filter(a => a.effect?.getTiming().iterations !== Infinity).map(a => a.finished.catch(() => {}))); return null; }");
  const add = async (path: string) => {
    await browser.keyboard.press("Control+k");
    await palette.getByRole("combobox").fill("> Add project");
    await palette.getByText("Add project", { exact: true }).tap();
    await palette.getByRole("option", /^Local folder/).tap();
    await palette.getByRole("combobox").fill(path);
    await screen.getByRole("button", /^(?:Create & )?Add \(Enter\)/).waitFor();
    await browser.keyboard.press("Enter");
  };
  await add(`${folder}/..`);
  await screen.getByRole("heading", /What should we build in/).waitFor();
  let titleFailure: unknown;
  try {
    await expect(browser.locator("[data-draft-project-trigger]")).toHaveText("code");
  } catch (error) { titleFailure = error; }
  await settle();
  await app.screenshot("parent-folder-title");
  await add(folder);
  await screen.getByRole("button", "New thread in app", { exact: true }).waitFor();
  await t3.open(thread);
  await screen.getByTestId("composer-editor").waitFor();
  await add(`${folder}/.`);
  await browser.evaluate(`() => new Promise(resolve => {
    const ready = () => document.body.innerText.includes("Failed to add project") || document.querySelector("[data-draft-project-trigger]")?.textContent?.trim() === "app";
    if (ready()) return resolve(null);
    const observer = new MutationObserver(() => { if (ready()) { observer.disconnect(); resolve(null); } });
    observer.observe(document.body, { subtree: true, childList: true, characterData: true });
  })`);
  await settle();
  await app.screenshot("existing-project-result");
  await expect(browser.locator("[data-draft-project-trigger]")).toHaveText("app");
  if (titleFailure) throw titleFailure;
});
