import { expect } from "e2e";
import { test, WEB, makeState, runPromise } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";

test("Retained fork keeps inherited item count after source deletion", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Fork count proof");
  const source = await t3.thread({ project, title: "Source alpha", messages: ["alpha"], model: "showcase" });
  const cli = makeState(T3_HOME).cli;
  const list = async () => JSON.parse((await runPromise(cli(["thread", "list", "--project", project, "--json"]))).stdout);
  await t3.open(source);
  await screen.getByRole("button", "Fork from this response").last().tap();
  await screen.getByRole("button", "Thread actions for Source alpha fork").waitFor({ state: "visible" });
  const fork = (await list()).find((thread: any) => thread.threadId !== source.threadId);
  await t3.open(source);
  await screen.getByRole("button", "Thread actions for Source alpha").tap();
  await screen.getByText("Delete", { exact: true }).tap();
  await screen.getByRole("button", "Confirm", { exact: true }).tap();
  await screen.getByRole("button", "Source alpha, Fork count proof", { exact: true }).waitFor({ state: "hidden" });
  await t3.open({ threadId: fork.threadId });
  await screen.getByRole("button", "Thread actions for Source alpha fork").waitFor({ state: "visible" });
  const listed = await list();
  const shell = listed.find((thread: any) => thread.threadId === fork.threadId);
  const full = JSON.parse((await runPromise(cli(["thread", "show", fork.threadId, "--json"]))).stdout);
  const evidence = { listItemCount: shell.itemCount, fullReadItemCount: full.thread.itemCount, sourceHidden: !listed.some((thread: any) => thread.threadId === source.threadId), inheritedMessages: full.messages.map((message: any) => message.role) };
  console.log("Retained fork observation", JSON.stringify(evidence));
  await browser.evaluate((data) => {
    const panel = document.createElement("pre");
    panel.textContent = "CLI observation (live)\nAfter source deletion\n" + JSON.stringify(data, null, 2);
    panel.style.cssText = "position:fixed;bottom:24px;right:24px;z-index:99999;background:#101820;color:#fff;padding:24px;border:2px solid #5ac8fa;border-radius:8px;font:14px/1.5 monospace;width:310px";
    document.body.append(panel);
  }, evidence);
  await app.screenshot("retained-fork-count");
  expect(evidence.listItemCount).toEqual(evidence.fullReadItemCount);
});
