import { execFileSync } from "node:child_process";
import { mkdir, writeFile } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Repeat import counts only the newly created Claude thread", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("Starter");
  const project = process.env.CLAUDE_CONFIG_DIR! + "/../demo-project";
  await mkdir(project, { recursive: true });
  execFileSync("git", ["init", "--quiet", "--initial-branch=main", project]);
  await browser.addInitScript(() => {
    document.addEventListener("DOMContentLoaded", () => {
      const style = document.createElement("style");
      style.textContent = ".font-mono > span.truncate:first-child { display: none !important; }";
      document.head.appendChild(style);
    });
  });
  const root = process.env.CLAUDE_CONFIG_DIR! + "/projects/demo";
  await mkdir(root, { recursive: true });
  await writeFile(root + "/22222222-2222-4222-8222-222222222222.jsonl", "{}\n");
  const transcript = async (id: string, title: string) => {
    const timestamp = new Date().toISOString();
    const records = [
      { type: "user", uuid: id + "-user", sessionId: id, cwd: project, timestamp, message: { role: "user", content: title } },
      { type: "assistant", uuid: id + "-assistant", parentUuid: id + "-user", sessionId: id, cwd: project, timestamp, message: { role: "assistant", content: [{ type: "text", text: "Synthetic conversation complete." }] } },
    ];
    await writeFile(root + "/" + id + ".jsonl", records.map(record => JSON.stringify(record)).join("\n") + "\n");
  };
  await transcript("11111111-1111-4111-8111-111111111111", "First synthetic conversation");
  await t3.open("/welcome");
  await screen.getByRole("button", "Add more agents").tap();
  await screen.getByRole("button", "Turn on: Claude").tap();
  await screen.getByRole("button", "Review all 1").tap();
  await screen.getByRole("button", "Select all", { exact: true }).tap();
  await app.screenshot("first-import-selection");
  await screen.getByRole("button", /Import.*and start/).tap();
  const toast = screen.getByText("Imported 1 thread", { exact: true });
  await toast.waitFor({ state: "visible" });
  await app.screenshot("first-import-result");
  await toast.waitFor({ state: "hidden" });
  await transcript("22222222-2222-4222-8222-222222222222", "Second synthetic conversation");
  await t3.open("/settings/about");
  await screen.getByRole("link", "Open", { exact: true }).tap();
  await screen.getByRole("button", "Review all 1").tap();
  await screen.getByRole("button", "Select all", { exact: true }).tap();
  await app.screenshot("repeat-import-selection");
  await screen.getByRole("button", "Import threads and start").tap();
  await screen.getByText(/Imported [12] threads?/).waitFor({ state: "visible" });
  await app.screenshot("repeat-import-result");
  await expect(screen.getByText("Imported 1 thread", { exact: true })).toBeVisible();
});
