/// <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";

const markdown = [
  "[lower-site](https://example.com/)",
  "Uppercase link: [UPPER-site](HTTPS://example.com/)",
  "Mixed link: [Mixed-site](HtTpS://example.com/)",
  "![lower-img](https://avatars.githubusercontent.com/u/9919?s=64)",
  "![UPPER-img](HTTPS://avatars.githubusercontent.com/u/9919?s=64)",
  'Themed image: <picture><source media="(prefers-color-scheme: dark)" srcset="HTTPS://avatars.githubusercontent.com/u/9919?s=64"><source media="(prefers-color-scheme: light)" srcset="HtTpS://avatars.githubusercontent.com/u/9919?s=64"><img alt="themed-img" src="HTTPS://avatars.githubusercontent.com/u/9919?s=64"></picture>',
  "Disallowed: [unsafe-link](JAVASCRIPT:alert(1)) ![unsafe-img](JAVASCRIPT:alert(1))",
].join("\n\n");

test("HTTP(S) Markdown destinations survive scheme casing", WEB, async ({ t3, app, browser, screen }) => {
  const fixture = path.join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await fs.readFile(fixture, "utf8");
  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:markdown}}}}},
    {type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}},
  ].map(x => JSON.stringify(x)).join("\n");
  try {
    await fs.writeFile(fixture, transcript);
    const project = await t3.project("Markdown URLs");
    const thread = await t3.thread({project,title:"HTTP scheme casing",model:"showcase",messages:["Show the lowercase, uppercase and mixed-case Markdown links and images verbatim."]});
    await t3.open(thread);
    await screen.getByText("Uppercase link:", {exact:false}).waitFor();
    // Let every surviving image finish its real network request before capturing.
    await browser.evaluate(async () => {
      await Promise.all([...document.images].map(img => img.complete ? Promise.resolve() : new Promise<void>(resolve => {img.addEventListener("load",()=>resolve(),{once:true});img.addEventListener("error",()=>resolve(),{once:true});})));
      return null;
    });
    for (const colorScheme of ["dark", "light"] as const) {
      await browser.emulateMedia({colorScheme});
      await app.screenshot(`markdown-${colorScheme}`);
    }
    const observed = await browser.evaluate(() => ({
      links: ["lower-site","UPPER-site","Mixed-site"].map(label => [...document.querySelectorAll("a")].find(a => a.textContent === label)?.getAttribute("href") ?? null),
      images: ["lower-img","UPPER-img","themed-img"].map(alt => {const img = [...document.images].find(i => i.alt === alt);return !!img && img.complete && img.naturalWidth > 0;}),
      unsafe: [...document.querySelectorAll("a,img")].some(el => /javascript:/i.test(el.getAttribute("href") ?? el.getAttribute("src") ?? "")),
    }));
    expect(observed).toEqual({links:["https://example.com/","https://example.com/","https://example.com/"],images:[true,true,true],unsafe:false});
  } finally { await fs.writeFile(fixture,original); }
});
