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

const sentence = "The purple walrus juggles seventeen lanterns at midnight.";
const rtf = String.raw`{\rtf1\ansi The purple walrus juggles seventeen lanterns at midnight.}`;
const exec = promisify(execFile);

test("Guest documents receive extracted text like owner documents", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Document proof", { "owner-note.rtf": rtf, "guest-note.rtf": rtf });
  const thread = await t3.thread({ project, title: "Read attached documents", messages: ["Start"] });
  try {
    await t3.open("/settings/labs");
    await screen.getByRole("switch", "Guest links").tap();
    await t3.open(thread);
    await screen.getByText("first fixture turn complete", { exact: false }).textContent();
    await browser.locator('input[type="file"]').setInputFiles(`${project}/owner-note.rtf`);
    await screen.getByTestId("composer-editor").tap();
    await browser.keyboard.press("End");
    await browser.keyboard.type("Please quote the attached owner note.");
    await screen.getByRole("button", "Submit message", { exact: true }).tap();
    await screen.getByText("second fixture turn complete", { exact: false }).textContent();
    const dir = `${T3_HOME}/userdata/attachments`;
    const ownerFiles = await readdir(dir);
    const owner = ownerFiles.find(name => name.endsWith(".rtf"))!;

    await new Promise<void>((resolve, reject) => {
      const watcher = watch(T3_HOME, (_event, filename) => {
        if (filename === "relay-ready") { watcher.close(); resolve(); }
      });
      watcher.on("error", reject);
      void readFile(`${T3_HOME}/relay-ready`).then(() => { watcher.close(); resolve(); }).catch(() => {});
    });
    await browser.keyboard.press("Control+k");
    await screen.getByPlaceholder("Search commands, projects, and threads...").fill("Share with guest");
    await screen.getByText("Share with guest", { exact: true }).tap();
    // Keep the one-use credential out of recordings.
    await browser.evaluate(() => {
      const style = document.createElement("style");
      style.textContent = 'input[aria-label="Guest link"] { color: transparent !important; }';
      document.head.append(style);
    });
    await screen.getByRole("button", "Create link", { exact: true }).tap();
    const link = await screen.getByLabel("Guest link").inputValue();
    await screen.getByRole("button", "Done", { exact: true }).tap();
    // The relay origin has no owner session; the guest authenticates only with the invitation.
    await app.open(link);
    await screen.getByLabel("Your name").fill("Guest Tester");
    await screen.getByRole("button", "Join", { exact: true }).tap();
    await browser.locator('input[type="file"]').setInputFiles(`${project}/guest-note.rtf`);
    await screen.getByPlaceholder("Message", { exact: true }).fill("Please quote the attached guest note.");
    await screen.getByRole("button", "Send", { exact: true }).tap();
    await screen.getByText("Waiting for", { exact: false }).first().textContent();
    await app.screenshot("guest-submitted");
    await t3.open(thread);
    await screen.getByRole("button", "Send message from Guest Tester").tap();
    await screen.getByText("first fixture turn complete", { exact: false }).nth(1).textContent();
    await screen.getByRole("button", "Submit message", { exact: true }).textContent();
    await app.screenshot("owner-sent-guest-document");

    const files = await readdir(dir);
    const guest = files.find(name => name.endsWith(".rtf") && !ownerFiles.includes(name))!;
    const ownerText = await readFile(`${dir}/${owner}.txt`, "utf8").catch(() => "MISSING");
    const guestText = await readFile(`${dir}/${guest}.txt`, "utf8").catch(() => "MISSING");
    const promptLog = await readFile(process.env.T3_SCENARIO_PROMPT_LOG!, "utf8");
    const prompts = promptLog.split("\n").filter(Boolean).map(line => JSON.parse(line)).filter(frame => frame.method === "session/prompt");
    const prompt = JSON.stringify(prompts.at(-1)?.params?.prompt ?? []);
    const reference = prompt.includes(`${guest}.txt`);
    const providerText = (prompts.at(-1)?.params?.prompt ?? []).map((part: { text?: string }) => part.text ?? "").join("\n");
    const providerLine = (providerText.split("\n").find((line: string) => line.includes('Attached file "guest-note.rtf"')) ?? "No guest attachment path in provider input").replaceAll(dir, "<attachments>").replaceAll(guest, "<guest-id>.rtf");
    const report = [
      "# Live server attachment inspection", "",
      "Same RTF sentence uploaded by owner, then by Guest Tester over the test relay.", "",
      "## Owner attachment", "",
      `Original RTF: ${files.includes(owner) ? "stored" : "MISSING"}`,
      `Extracted .rtf.txt: ${ownerText === "MISSING" ? "MISSING" : "present"}`, "",
      ownerText, "", "## Guest attachment (after owner pressed Send)", "",
      `Original RTF: ${files.includes(guest) ? "stored" : "MISSING"}`,
      `Extracted .rtf.txt: ${guestText === "MISSING" ? "MISSING" : "present"}`, "",
      guestText, "", `Provider input references guest .rtf.txt: ${reference ? "YES" : "NO"}`, "",
      "```text", providerLine, "```", "",
      "Observed from the running server's attachment directory and the replay provider's incoming protocol; no database writes or mocked uploads.",
    ].join("\n");
    await writeFile(`${project}/attachment-evidence.md`, report);
    await writeFile(`${T3_HOME}/attachment-evidence.md`, report);
    if (process.env.T3_SCENARIO_ARTIFACT_ROOT) {
      const { stdout } = await exec("git", ["rev-parse", "HEAD"], { cwd: APP_DIR });
      await writeFile(`${process.env.T3_SCENARIO_ARTIFACT_ROOT}/${stdout.trim().slice(0, 10)}-attachment-evidence.md`, report);
    }
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill("attachment-evidence.md");
    await screen.getByRole("option", "attachment-evidence.md", { exact: false }).tap();
    await screen.getByText("Live server attachment inspection", { exact: false }).first().textContent();
    await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
    await screen.getByRole("button", "Hide file explorer", { exact: true }).tap();
    await app.screenshot("attachment-extraction");
    expect(guestText).toContain(sentence);
    expect(reference).toBe(true);
  } finally {
    await exec(process.execPath, ["apps/server/src/bin.ts", "connect", "logout", "--base-dir", T3_HOME], { cwd: APP_DIR, env: process.env }).catch(() => {});
  }
});
