/// <reference lib="dom" />
import { readFile, writeFile } from "node:fs/promises";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const cases = [
  { title: "Repro 1", text: "<!--\n★ Insight ───\n-->\n\n★ Insight ───\nreal insight\n───\n\nAfter", insight: true, paragraph: "After" },
  { title: "Repro 2", text: "<!--\n★ Insight ───\n-->\n\nVisible text", insight: false, paragraph: "Visible text" },
  { title: "Control", text: "★ Insight ───\nreal insight\n───\n\nAfter", insight: true, paragraph: "After" },
];
test("HTML comments do not open Insight callouts", WEB, async ({t3, app, browser, screen}) => {
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await readFile(fixture, "utf8");
  const project = await t3.project("Markdown rendering");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client.subscribeServerConfig({}).pipe(Stream.filter(event => {
      const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
      return providers.some(p => p.instanceId === "devReplay" && p.models?.some(m => m.slug === "showcase"));
    }), Stream.runHead);
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const results = [];
  try {
    for (const sample of cases) {
      const transcript = [
        {type:"expect_outbound",frame:{kind:"request",method:"session/prompt"}},
        {type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"replay",update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:sample.text}}}}},
        {type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}},
      ].map(x=>JSON.stringify(x)).join("\n");
      await writeFile(fixture, transcript);
      const thread = await t3.thread({project,title:sample.title,model:"showcase",messages:["Show the Markdown rendering sample."]});
      await t3.open(thread);
      await screen.getByText(sample.paragraph, {exact:true}).waitFor();
      await screen.getByText("Syncing messages...", {exact:true}).waitFor({state:"hidden"});
      await app.screenshot(sample.title);
      results.push(await browser.evaluate((sample) => ({
        insight: document.querySelectorAll('[data-markdown-alert="insight"]').length === (sample.insight ? 1 : 0),
        paragraph: [...document.querySelectorAll('p')].some(p=>p.textContent===sample.paragraph && !p.closest('blockquote, [data-markdown-alert]')),
      }), sample));
    }
  } finally { await writeFile(fixture, original); }
  expect(results).toEqual(cases.map(()=>({insight:true,paragraph:true})));
});
