/// <reference lib="dom" />
// @effect-diagnostics nodeBuiltinImport:off -- This scenario stages a symlink and a replay transcript.
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Both absolute spellings of a page under a symlinked workspace load sibling CSS and JavaScript", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("demo");
  const parent = path.dirname(project);
  const realParent = `${parent}-real`;
  await fs.rename(parent, realParent);
  await fs.symlink(realParent, parent, "dir");
  const realProject = await fs.realpath(project);
  const folder = path.join(realProject, ".git/t3-repro");
  await fs.mkdir(folder, { recursive: true });
  await fs.writeFile(path.join(folder, "index.html"), `<!doctype html><html><head><meta charset="utf-8"><title>Sibling asset proof</title><link rel="stylesheet" href="style.css"></head><body><main><h1>Sibling asset proof</h1><p>HTML loaded</p><p id="css">CSS: missing</p><p id="js">JavaScript: missing</p></main><p id="ready">Loading page</p><script src="app.js"></script><script>window.addEventListener("load", () => { document.querySelector("#css").textContent = getComputedStyle(document.body).backgroundColor === "rgb(232, 250, 240)" ? "CSS: loaded" : "CSS: missing"; document.querySelector("#ready").textContent = "Page load complete"; });</script></body></html>`);
  await fs.writeFile(path.join(folder, "style.css"), `body { background: #e8faf0; color: #153d2b; font: 20px system-ui; margin: 32px; } main { border: 3px solid #23844f; border-radius: 12px; padding: 24px; } #css { font-size: 0; } #css::after { content: "CSS: loaded"; font-size: 20px; }`);
  await fs.writeFile(path.join(folder, "app.js"), `document.querySelector('#js').textContent = 'JavaScript: loaded';`);
  const transcript = path.join(APP_DIR, "apps/server/scripts/dev-replay/command_output_transcript.ndjson");
  const original = await fs.readFile(transcript, "utf8");
  const text = `Open the same page by either spelling:\n\n[Real path page](${realProject}/.git/t3-repro/index.html)\n\n[Symlink path page](${project}/.git/t3-repro/index.html)`;
  const frames = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "replay", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  try {
    await fs.writeFile(transcript, frames.map(frame => JSON.stringify(frame)).join("\n") + "\n");
    const thread = await t3.thread({ project, title: "Symlink workspace page", model: "command-output", messages: ["Show both page links."] });
    await t3.open(thread);
    const results = [];
    // Check the working spelling first so a base failure cannot skip that control capture.
    for (const spelling of ["Symlink", "Real"]) {
      const destination = `${spelling === "Real" ? realProject : project}/.git/t3-repro/index.html`;
      await browser.locator(`a[href="${destination}"]`).tap();
      const preview = browser.frameLocator('iframe[title$="index.html"]');
      await preview.locator("h1").waitFor();
      await preview.getByText("Page load complete", { exact: true }).waitFor();
      results.push({
        javascript: await preview.locator("#js").textContent(),
        css: await preview.locator("#css").textContent(),
      });
      await app.screenshot(`${spelling.toLowerCase()}-path-page`);
    }
    expect(results).toEqual([
      { javascript: "JavaScript: loaded", css: "CSS: loaded" },
      { javascript: "JavaScript: loaded", css: "CSS: loaded" },
    ]);
  } finally {
    await fs.writeFile(transcript, original);
  }
});
