import { readFile, writeFile } from "node:fs/promises";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

// The replay agent emits native subagent metadata through the real ACP adapter.
const result = "![screenshot](shot.png) Verified [docs](https://en.wikipedia.org/wiki/T3_(protocol)) [report](outputs/report%20(final).md)";
const prompt = `Spawn exactly one subagent whose task is to reply with exactly \`${result}\`, wait for it, then reply 'done'.`;
const update = (value: object) => ({ type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "replay", update: value } } });

test("Subagent preview keeps image alt text and labels without link destinations", WEB, async ({ t3, app, screen }) => {
  const transcript = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await readFile(transcript, "utf8");
  const frames = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    update({ sessionUpdate: "tool_call", toolCallId: "exact-reply", kind: "other", title: "Exact Reply", status: "in_progress", _meta: { "cognition.ai/subagent_started": { agentId: "exact-reply-child", title: "Exact Reply", task: prompt } } }),
    update({ sessionUpdate: "tool_call_update", toolCallId: "exact-reply", status: "completed", _meta: { "cognition.ai/subagent_completed": { agentId: "exact-reply-child", success: true, summary: result } }, content: [{ type: "content", content: { type: "text", text: result } }] }),
    update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "done" } }),
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  try {
    await writeFile(transcript, frames.map((frame) => JSON.stringify(frame)).join("\n") + "\n");
    const project = await t3.project("preview-demo");
    const thread = await t3.thread({ project, title: "Subagent markdown preview", messages: [prompt], model: "showcase", provider: "proofReplay" });
    await t3.open(thread);
    await screen.getByRole("button", "Dismiss Replay subagent provider error").tap();
    await screen.getByRole("button", /Worked for/).tap();
    await app.screenshot("subagent-preview");
    await expect(screen.getByText("screenshot Verified docs report", { exact: true })).toBeVisible();
  } finally {
    await writeFile(transcript, original);
  }
});
