/// <reference lib="dom" />
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("Lone CR insight framing becomes a callout", WEB, async ({t3, app, browser, screen}) => {
  const recording = path.join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await fs.readFile(recording, "utf8");
  const entries = [
    {type:"expect_outbound",frame:{kind:"request",method:"session/prompt",params:"<any>"}},
    {type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"dev-replay-session",update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"★ Insight ─────\rCache is warm.\r─────\rAfter."}}}}},
    {type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}}
  ];
  try {
    await fs.writeFile(recording, entries.map(x=>JSON.stringify(x)).join("\n")+"\n");
    const project = await t3.project("Insight demo");
    const thread = await t3.thread({project,title:"CR insight",messages:["go"],model:"showcase"});
    await browser.emulateMedia({colorScheme:"dark"});
    await t3.open(thread);
    await screen.getByText("Cache is warm.", {exact:false}).waitFor();
    await screen.getByText("Syncing messages...", {exact:false}).waitFor({state:"hidden"});
    await app.screenshot("cr-insight");
    const rendered = await browser.evaluate(() => {
      const callout = document.querySelector('[data-markdown-alert="insight"]');
      return {body:callout?.textContent?.replace(/\s+/g, " ").trim() ?? null, afterInside:callout?.textContent?.includes("After.") ?? false, markers:[...document.querySelectorAll("p")].some(p=>p.textContent?.includes("─────")), afterOutside:[...document.querySelectorAll("p")].some(p=>p.textContent==="After." && !p.closest('[data-markdown-alert="insight"]'))};
    });
    expect(rendered).toEqual({body:"Insight Cache is warm.",afterInside:false,markers:false,afterOutside:true});
  } finally { await fs.writeFile(recording, original); }
});
