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

const source = (name: string) => `---\ntitle: Hidden ${name} metadata\n---\n# ${name} guide\n\n**Bold example**\n\n- First item\n- Second item`;
const prompt = `This is a UI rendering demonstration. Do not inspect files, change files, or run commands. First call the T3 send_to_user MCP tool exactly once, with this message:\nSent-message example\n\n\`\`\`md\n${source("Sent")}\n\`\`\`\n\nThen reply in your normal final answer with this exact fenced block first:\n\`\`\`markdown\n${source("Reply")}\n\`\`\`\n\nAfter that block, also include this exact second block:\n\`\`\`md\n${source("Alias")}\n\`\`\`\n\nThen write the words 'Streaming appendix' followed by a single paragraph counting from 1 to 900, separated by spaces. This long appendix lets us observe the block while you are still streaming. End with 'Demonstration complete'. Follow these instructions exactly.`;

test("Markdown fences render, copy original frontmatter, and return to source", WEB, async ({t3, app, browser, screen}) => {
  const capture = async (label: string) => {
    // Hold each demonstration state at normal speed so its recording can be reviewed.
    await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 1500)); return null; });
    await app.screenshot(label);
  };
  const block = (language: string) => language === "alias" ? browser.locator('.chat-markdown-codeblock[data-language="md"]').nth(1) : browser.locator(`.chat-markdown-codeblock[data-language="${language}"]`).first();
  const copyAndPaste = async (language: string, name: string, label: string) => {
    await block(language).getByRole("button", "Copy code").tap();
    await block(language).getByRole("button", "Copied").waitFor();
    expect(await browser.evaluate(() => navigator.clipboard.readText())).toBe(source(name));
    await screen.getByRole("textbox").tap();
    await browser.keyboard.press("ControlOrMeta+V");
    await capture(label);

    await screen.getByRole("textbox").fill("");
  };
  const project = await t3.project("markdown-demo");
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await readFile(settingsPath, "utf8"));
  settings.providerInstances.opencode = { driver: "opencode", enabled: true, config: { binaryPath: "opencode" } };
  await writeFile(settingsPath, JSON.stringify(settings));
  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 === "opencode" && provider.enabled)), Stream.runHead);
  }).pipe(Effect.scoped));
  await t3.open("/settings/chat");
  await screen.getByRole("switch", "Rich text composer").uncheck();
  const { cli } = makeState(T3_HOME);
  const launched = await runPromise(cli(["thread", "start", project, prompt, "--title", "Markdown preview demonstration", "--provider", "opencode", "--model", "openai/gpt-6-luna", "--json"]));
  const { threadId } = JSON.parse(launched.stdout);
  await t3.open({threadId});
  await screen.getByText("Streaming appendix", {exact:false}).waitFor({timeout:120000});
  // Keep the reply's fence in view while later text is still arriving.
  await browser.evaluate(() => {
    document.querySelector('.chat-markdown-codeblock[data-language="markdown"]')?.scrollIntoView({block:"center"});
    return null;
  });
  await screen.getByRole("button", "Stop generation").waitFor();
  await expect(block("markdown").getByRole("button", "Show rendered markdown")).toHaveCount(0);
  await capture("reply-mid-stream");
  await screen.getByRole("button", "Stop generation").waitFor({state:"hidden",timeout:180000});
  await browser.evaluate(() => {
    document.querySelector('.chat-markdown-codeblock[data-language="markdown"]')?.scrollIntoView({block:"center"});
    return null;
  });
  await capture("reply-finished-source");
  await block("alias").scrollIntoView();
  await capture("reply-md-alias-finished-source");
  await block("md").scrollIntoView();
  await capture("sent-md-finished-source");
  await expect(screen.getByRole("button", "Show rendered markdown")).toHaveCount(3);
  await block("markdown").scrollIntoView();
  await copyAndPaste("markdown", "Reply", "reply-source-copy-original");
  await block("markdown").getByRole("button", "Show rendered markdown").tap();
  await expect(screen.getByRole("heading", "Reply guide", {exact:true})).toBeVisible();
  await expect(block("markdown").getByText("title: Hidden Reply metadata", {exact:false})).toHaveCount(0);
  await capture("reply-rendered-frontmatter-masked");
  await copyAndPaste("markdown", "Reply", "reply-rendered-copy-original");
  await block("markdown").getByRole("button", "Show markdown source").tap();
  await capture("reply-returned-source");
  await block("alias").scrollIntoView();
  await capture("reply-md-alias-source");
  await copyAndPaste("alias", "Alias", "reply-md-alias-source-copy-original");
  await block("alias").getByRole("button", "Show rendered markdown").tap();
  await expect(screen.getByRole("heading", "Alias guide", {exact:true})).toBeVisible();
  await expect(block("alias").getByText("title: Hidden Alias metadata", {exact:false})).toHaveCount(0);
  await capture("reply-md-alias-rendered");
  await copyAndPaste("alias", "Alias", "reply-md-alias-rendered-copy-original");
  await block("alias").getByRole("button", "Show markdown source").tap();
  await capture("reply-md-alias-returned-source");
  await block("md").scrollIntoView();
  await copyAndPaste("md", "Sent", "sent-md-source-copy-original");
  await block("md").getByRole("button", "Show rendered markdown").tap();
  await expect(screen.getByRole("heading", "Sent guide", {exact:true})).toBeVisible();
  await expect(block("md").getByText("title: Hidden Sent metadata", {exact:false})).toHaveCount(0);
  await capture("sent-md-rendered-frontmatter-masked");
  await copyAndPaste("md", "Sent", "sent-md-rendered-copy-original");
  await block("md").getByRole("button", "Show markdown source").tap();
  await capture("sent-md-returned-source");
});
