/// <reference lib="dom" />
import { expect } from "e2e";
import { readdir, rename, stat } from "node:fs/promises";
import { join } from "node:path";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("A missing large text attachment hides Copy contents and recovers on retry", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("trace-demo");
  const thread = await t3.thread({ project, title: "Trace investigation", model: "showcase", messages: ["Start"] });
  await t3.open(thread);
  const selector = '[data-chat-composer-form] input[type="file"]';
  await browser.locator(selector).waitFor({ state: "attached" });
  await screen.getByRole("textbox").fill("Here is the trace log");
  await browser.evaluate((selector) => {
    const picker = document.querySelector<HTMLInputElement>(selector)!;
    const line = "2026-11-28 INFO synthetic trace: request completed successfully\n";
    const text = line.repeat(Math.ceil(1258046 / line.length)).slice(0, 1258046);
    const files = new DataTransfer();
    files.items.add(new File([text], "server-trace.log", { type: "text/plain" }));
    picker.files = files.files;
    picker.dispatchEvent(new Event("change", { bubbles: true }));
    return null;
  }, selector);
  await screen.getByRole("button", "File attachment, server-trace.log, 1.2 MB", { exact: true }).waitFor();
  await screen.getByRole("button", "Submit message", { exact: true }).tap();
  await screen.getByRole("button", "Fork from this response").nth(1).waitFor();
  const directory = join(T3_HOME, "userdata", "attachments");
  const files = await readdir(directory, { recursive: true });
  let stored = "";
  for (const file of files) {
    const path = join(directory, file);
    if ((await stat(path)).isFile() && (await stat(path)).size === 1258046) stored = path;
  }
  if (!stored) throw new Error("Uploaded synthetic log was not stored");
  const moved = join(T3_HOME, "missing-trace.log");
  await rename(stored, moved);
  try {
    await screen.getByRole("button", "server-trace.log", { exact: false }).tap();
    await screen.getByText("Attachment was not found.", { exact: true }).waitFor();
    await app.screenshot("authorization-failed");
    const count = await screen.getByRole("button", "Copy contents", { exact: true }).count();
    if (count) {
      await screen.getByRole("button", "Copy contents", { exact: true }).tap();
      await screen.getByText("Wait for the file to finish loading before copying.", { exact: true }).waitFor();
      await browser.evaluate(async () => { await Promise.all(document.getAnimations().map((animation) => animation.finished.catch(() => {}))); return null; });
      await app.screenshot("misleading-copy-instruction");
      await screen.getByText("Wait for the file to finish loading before copying.", { exact: true }).waitFor({ state: "hidden" });
    }
    await rename(moved, stored);
    await screen.getByRole("button", "Try again", { exact: true }).tap();
    await screen.getByRole("button", "Save file", { exact: true }).waitFor();
    await screen.getByText("2026-11-28 INFO synthetic trace: request completed successfully", { exact: true }).first().waitFor();
    await app.screenshot("successful-retry");
    await expect(count).toBe(0);
    await expect(screen.getByRole("button", "Copy contents", { exact: true })).toHaveCount(1);
  } finally {
    try { await rename(moved, stored); } catch {}
  }
});
