import { expect } from "e2e";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
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";

test("One leading BOM preserves Insight callouts and their find text", WEB, async ({t3, app, screen, browser}) => {
  const replies = [
    "★ Insight ───\nThe note\n───",
    "\uFEFF★ Insight ───\nThe note\n───",
    "★ Insight ───\nfirst line\nsecond line\n───",
    "\uFEFF★ Insight ───\nfirst line\nsecond line\n───",
    "Intro\n\n\uFEFF★ Insight ───\nThe note\n───",
    "\uFEFF\uFEFF★ Insight ───\nSecond BOM remains text\n───",
  ];
  const fixture = join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await readFile(fixture, "utf8");
  const frames = replies.flatMap(text => [
    {type:"expect_outbound",frame:{kind:"request",method:"session/prompt",params:{}}},
    {type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"insight",update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text}}}}},
    {type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}},
  ]);
  await writeFile(fixture, frames.map(frame => JSON.stringify(frame)).join("\n")+"\n");
  try {
    const project = await t3.project("insight-demo");
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl!);
      yield* client.subscribeServerConfig({}).pipe(
        Stream.filter(event => (event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : []).some(provider => provider.instanceId === "devReplay" && provider.models?.some(model => model.slug === "showcase"))),
        Stream.runHead,
      );
    }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
    const thread = await t3.thread({project,title:"Insight BOM comparison",model:"showcase",messages:replies.map((_,i)=>`Example ${i+1}`)});
    await t3.open(thread);
    await screen.getByText("Second BOM remains text", {exact:false}).waitFor();
    await screen.getByText("Syncing messages...", {exact:false}).waitFor({state:"hidden"});
    await browser.locator('[data-markdown-alert="insight"]').first().scrollIntoView();
    await app.screenshot("insight-first-callouts");
    await screen.getByText("Second BOM remains text", {exact:false}).scrollIntoView();
    await app.screenshot("insight-callouts");
    await browser.keyboard.press("Control+f");
    await screen.getByRole("searchbox", "Find in thread").fill("★ Insight");
    try { await expect.poll(() => browser.evaluate(`JSON.stringify({callouts:document.querySelectorAll('[data-markdown-alert="insight"]').length, breaks:[...document.querySelectorAll('[data-markdown-alert="insight"]')].filter(e=>e.textContent.includes('first line') && e.querySelector('br')).length,find:document.querySelector('[data-thread-find-bar] span[aria-hidden]')?.textContent})`)).toBe(JSON.stringify({callouts:4,breaks:2,find:"1/2"})); } finally { await app.screenshot("insight-find"); }
  } finally { await writeFile(fixture,original); }
});
