/// <reference lib="dom" />
import { expect } from "e2e";
import { readFile, writeFile } from "node:fs/promises";
import { spawnSync } from "node:child_process";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Theme publication preserves a directory at nightfall.json", WEB, async ({ t3, app, browser, screen }) => {
  const initialSettings = '{"defaultTheme":"light"}\n';
  const project = await t3.project("theme-collision", {
    "theme-home/userdata/themes/nightfall.json/notes.txt": "These notes must remain at their original path.\n",
    "theme-home/userdata/settings.json": initialSettings,
    "nightfall.json": '{"name":"Nightfall","appearance":"dark","canvas":"#1a1b26","accent":"#7aa2f7"}',
  });
  const thread = await t3.thread({ project, title: "Theme directory collision", messages: ["Start"] });
  const home = `${project}/theme-home`;
  const result = spawnSync(process.execPath, ["apps/server/src/bin.ts", "theme", "set", `${project}/nightfall.json`, "--base-dir", home], { cwd: APP_DIR, encoding: "utf8" });
  const notes = await readFile(`${home}/userdata/themes/nightfall.json/notes.txt`, "utf8").catch(() => "UNREADABLE AT ORIGINAL PATH");
  const settings = await readFile(`${home}/userdata/settings.json`, "utf8");
  const clean = (s: string) => s.replaceAll(project, ".").replace(/\u001b\[[0-9;]*m/g, "").split("\n").filter((line) => !/^\s+at /.test(line)).join("\n");
  await writeFile(`${project}/publication-result.txt`, [
    "$ t3 theme set ./nightfall.json --base-dir ./theme-home",
    `Exit: ${result.status}`, clean(result.stdout), clean(result.stderr),
    "Notes at theme-home/userdata/themes/nightfall.json/notes.txt:", notes,
    "Settings before:", initialSettings, "Settings after:", settings,
  ].join("\n"));
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  const clickRow = async (path: string) => browser.evaluate((path) => {
    for (const host of document.querySelectorAll("*")) {
      const row = host.shadowRoot?.querySelector<HTMLElement>(`[data-item-path="${path}"]`);
      if (row) { row.click(); return true; }
    }
    return false;
  }, path);
  await expect.poll(() => clickRow("publication-result.txt")).toBe(true);
  const editorText = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return "";
  });
  await expect.poll(editorText).toContain("Settings after:");
  await app.screenshot("publication-result");
  // Expand compact directory rows until the original destination is visible.
  for (let depth = 0; depth < 5; depth++) {
    await browser.evaluate(() => {
      for (const host of document.querySelectorAll("*")) {
        const rows = host.shadowRoot?.querySelectorAll<HTMLElement>('[data-item-path][aria-expanded="false"]');
        const row = Array.from(rows ?? []).find((r) => r.dataset.itemPath?.startsWith("theme-home"));
        if (row) { row.click(); return; }
      }
    });
    await browser.evaluate(() => new Promise((resolve) => setTimeout(resolve, 500)));
  }
  if (notes !== "UNREADABLE AT ORIGINAL PATH") {
    await clickRow("theme-home/userdata/themes/nightfall.json/notes.txt");
    await expect.poll(editorText).toContain("These notes must remain");
  } else {
    await clickRow("theme-home/userdata/themes/nightfall.json");
    await expect.poll(editorText).toContain("Nightfall");
  }
  await app.screenshot("original-notes-path");
  expect(result.status).not.toBe(0);
  expect(clean(result.stdout + result.stderr)).toContain("directory");
  expect(notes).toBe("These notes must remain at their original path.\n");
  expect(settings).toBe(initialSettings);
});
