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

test("Standalone pictures have loading and error frames while inline pictures stay inline", WEB, async ({t3, app, browser, screen}) => {
  let release!: () => void;
  const held = new Promise<void>(resolve => { release = resolve; });
  const url = "https://picture-demo.invalid";
  const routes: Promise<void>[] = [];
  await browser.route(`${url}/**`, async route => {
    let done!: () => void;
    routes.push(new Promise<void>(resolve => { done = resolve; }));
    try {
      if (route.request.url.includes("slow")) await held;
      await route.fulfill({status:404, body:"Missing image"});
    } finally { done(); }
  });
  const markdown = `## Failed images\n\n<p align="center"><picture><img src="${url}/missing-picture.png" alt="Picture logo (fails)"></picture></p>\n\n<p><img src="${url}/missing-bare.png" alt="Bare logo (fails)"></p>\n\n## Loading images\n\n<p align="center"><picture><img src="${url}/slow-picture.png" alt="Picture logo (loading)"></picture></p>\n\n<p><img src="${url}/slow-bare.png" alt="Bare logo (loading)"></p>\n\n## Root-level picture\n\n<picture>\n<source media="(prefers-color-scheme: dark)" srcset="${url}/missing-dark.png">\n<img src="${url}/missing-root.png" alt="Root picture (fails)">\n</picture>\n\nA paragraph after the root-level picture.\n\n## Inline picture\n\n<p>Some text <picture><img src="${url}/missing-inline.png" alt="Inline picture (fails)"></picture> after it.</p>\n\nEnd of picture demonstration.`;
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await readFile(fixture, "utf8");
  await writeFile(fixture, [
    {type:"expect_outbound", frame:{kind:"request",method:"session/prompt",params:{}}},
    {type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"picture-demo",update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:markdown}}}}},
    {type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}}
  ].map(value=>JSON.stringify(value)).join("\n"));
  try {
    await browser.setViewport({width:1440,height:1100});
    const project = await t3.project("Picture demonstration");
    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 thread = await t3.thread({project,title:"Standalone picture frames",model:"showcase",messages:["Show the picture image loading and failure demonstration."]});
    await t3.open(thread);
    await screen.getByText("End of picture demonstration.", {exact:true}).waitFor();
    await browser.mouse.move(700, 400);
    await browser.mouse.wheel(0, -3000);
    const results: Record<string,boolean> = {};
    for (const [label, heading] of [["failed-images","Failed images"],["loading-images","Loading images"],["root-and-inline","Root-level picture"]]) {
      await browser.evaluate((heading) => {
        [...document.querySelectorAll("h2")].find(el=>el.textContent===heading)?.scrollIntoView({block:"start"});
      }, heading);
      if (label === "failed-images") await screen.getByText("Image unavailable · Bare logo (fails)", {exact:false}).waitFor();
      if (label === "root-and-inline") await screen.getByText("Image unavailable · Root picture (fails)", {exact:false}).waitFor();
      await browser.evaluate((heading) => {
        [...document.querySelectorAll("h2")].find(el=>el.textContent===heading)?.scrollIntoView({block:"start",behavior:"instant"});
      }, heading);
      await app.screenshot(label);
    }
    Object.assign(results, await browser.evaluate(() => {
      const alertFor = (text:string) => [...document.querySelectorAll('[role="alert"]')].some(el=>el.textContent?.includes(text) && el.getBoundingClientRect().width >= 400 && el.getBoundingClientRect().height >= 200);
      const loading = document.querySelector('img[alt="Picture logo (loading)"]');
      const frame = loading?.closest('[role="status"]');
      const inline = [...document.querySelectorAll('span')].find(el=>el.textContent === 'Image unavailable · Inline picture (fails)');
      return {pictureError:alertFor('Picture logo (fails)'), bareError:alertFor('Bare logo (fails)'), rootError:alertFor('Root picture (fails)'), pictureLoading:!!frame && frame.getBoundingClientRect().width>=400 && frame.getBoundingClientRect().height>=200, inlineStaysInline:!!inline && !inline.closest('[role="alert"]')};
    }));
    await expect(results).toEqual({pictureError:true,bareError:true,rootError:true,pictureLoading:true,inlineStaysInline:true});
  } finally {
    await writeFile(fixture,original);
    release();
    await Promise.all(routes);
    await browser.unroute(`${url}/**`);
  }
});
