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

test("Completed workflow replies strip balanced link destinations", WEB, async ({t3,app,browser,screen}) => {
  await browser.setViewport({width:1600,height:900});
  const project = await t3.project("link-summary-demo");
  const replies = ["See [the issue](https://example.com/file(test)). Fixed.", 'Check [docs](<https://example.com/a(b)>) and [fn](https://example.com/foo(bar(1)) "title"). Next.'];
  const settingsPath = Path.join(T3_HOME,"userdata/settings.json");
  const settings = JSON.parse(await FS.readFile(settingsPath,"utf8"));
  settings.providerInstances.opencode = {driver:"opencode",enabled:true,config:{}};
  await FS.writeFile(settingsPath,JSON.stringify(settings));
  await runPromise(Effect.gen(function*(){ const client=yield* rpcClient(T3_HOME,app.baseUrl ?? ""); yield* client["server.updateSettings"]({patch:{workflowsEnabled:true}}); }).pipe(Effect.scoped));
  const definition = `export default T3.workflow("linkrepro", { version: 1, payload: Schema.Struct({}) }, Effect.fn(function* () { yield* T3.title("Link summary repro"); ${replies.map((reply,i)=>`yield* T3.agent(${JSON.stringify(i===0?"reply":"nested")}, {project:${JSON.stringify(project)},model:{instanceId:"opencode",model:"anthropic/claude-haiku-5-5"},brief:${JSON.stringify("Do not use tools. Reply with exactly this text, without code fences or any other words:\n"+reply)}});`).join("\n")} }));`;
  await FS.mkdir(Path.join(T3_HOME,"workflows"),{recursive:true});
  await FS.writeFile(Path.join(T3_HOME,"workflows/linkrepro.ts"),definition);
  const started=await runPromise(makeState(T3_HOME).cli(["workflow","start","linkrepro","--key","proof","--json"]));
  const {run}=JSON.parse(started.stdout);
  await t3.open(`/workflows?run=${run.runId}`);
  await screen.getByText("See the issue",{exact:false}).first().waitFor({timeout:120000});
  await screen.getByText("Check docs",{exact:false}).first().waitFor({timeout:120000});
  await browser.evaluate(async()=>{await document.fonts.ready; await Promise.all(Array.from(document.images).map(image=>image.decode().catch(()=>{})));});
  await screen.getByRole("button", "reply See the issue", {exact:false}).click();
  await screen.getByRole("link", "the issue", {exact:true}).waitFor();
  await browser.evaluate(async()=>{await document.fonts.ready; await Promise.all(Array.from(document.images).map(image=>image.decode().catch(()=>{})));});
  await app.screenshot("original-reply-loaded");
  await browser.evaluate(()=>new Promise(resolve=>setTimeout(resolve,500)));
  await app.screenshot("original-reply-stable");
  await screen.getByRole("button", "nested Check docs", {exact:false}).click();
  await screen.getByRole("link", "fn", {exact:true}).waitFor();
  await browser.evaluate(async()=>{await document.fonts.ready; await Promise.all(Array.from(document.images).map(image=>image.decode().catch(()=>{})));});
  await app.screenshot("nested-and-title-loaded");
  await browser.evaluate(()=>new Promise(resolve=>setTimeout(resolve,500)));
  await app.screenshot("nested-and-title-stable");
  await expect(screen.getByText("See the issue.",{exact:true})).toBeVisible();
  await expect(screen.getByText("Check docs and fn.",{exact:true})).toBeVisible();
});
