/// <reference lib="dom" />
import { expect } from "e2e";
import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const prompt = 'Use AskUserQuestion now to ask exactly one single-select question: "Which color should the README heading use?" with options Red (description: Use red) and Blue (description: Use blue). Do not read files or do anything else first. After the answer, reply exactly "Color: Blue; image received" if the answer included an attached image, otherwise reply exactly "Color: Blue; no image received". Do not print file paths. Then stop.';

test("Choosing Blue preserves an image-only answer and refuses when the draft is full", WEB, async ({t3, app, browser, screen}) => {
  await runPromise(Effect.gen(function*() {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({patch:{}, providerInstanceMutation:{operation:"upsert",instanceId:ProviderInstanceId.make("claudeAgent"),instance:{driver:ProviderDriverKind.make("claudeAgent"),enabled:true,config:{}}}});
  }).pipe(Effect.scoped));
  const project = await t3.project("Color demo");
  const { cli } = makeState(T3_HOME);
  const start = async (title:string, message:string) => {
    const result = await runPromise(cli(["thread","start",project,message,"--title",title,"--provider","claudeAgent","--model","claude-haiku-5-5","--wait","--json"],[0,2]));
    return JSON.parse(result.stdout) as {threadId:string};
  };
  const paste = async (count:number, prefix:string) => browser.evaluate(async ({count,prefix}) => {
    const canvas = new OffscreenCanvas(120,80);
    const ctx = canvas.getContext("2d")!;
    const data = new DataTransfer();
    for(let i=0;i<count;i++) {
      ctx.fillStyle = `hsl(${i*37},70%,50%)`; ctx.fillRect(0,0,120,80);
      ctx.fillStyle="white"; ctx.font="20px sans-serif"; ctx.fillText(String(i+1),15,45);
      data.items.add(new File([await canvas.convertToBlob({type:"image/png"})], `${prefix}${i+1}.png`, {type:"image/png"}));
    }
    document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste",{clipboardData:data,bubbles:true,cancelable:true}));
    return null;
  },{count,prefix});
  const images = () => browser.locator('[data-chat-composer-form="true"] button[aria-label^="Preview "]');
  // Run the capacity case first so both sides capture it before the final assertions.
  const full = await start("Full draft", "Reply exactly Ready and stop. Do not call tools.");
  await t3.open();
  await screen.getByText("Color demo",{exact:true}).first().waitFor();
  await t3.open(full);
  await screen.getByRole("textbox").tap();
  await paste(100,"draft-");
  await browser.locator('button[aria-label="Preview draft-100.png"]:enabled').waitFor();
  await runPromise(cli(["thread","send",full.threadId,prompt,"--wait","--json"],[2]));
  await screen.getByRole("button",{name:/^Blue\b/}).waitFor();
  await screen.getByRole("textbox").tap();
  await paste(1,"custom-");
  await browser.locator('button[aria-label="Preview custom-1.png"]:enabled').waitFor();
  await app.screenshot("full-draft-before-blue");
  await screen.getByRole("button",{name:/^Blue\b/}).tap();
  await browser.locator('text="The attachment limit has been reached."').or(browser.locator('text="Color: Blue; image received"')).or(browser.locator('text="Color: Blue; no image received"')).first().waitFor();
  await app.screenshot("full-draft-after-blue");
  const refused = await screen.getByText("The attachment limit has been reached.",{exact:true}).isVisible();
  const retained = await screen.getByRole("button",{name:/^Blue\b/}).isVisible();
  const customRetained = await browser.locator('button[aria-label="Preview custom-1.png"]').isVisible();

  const normal = await start("Image-only answer",prompt);
  await t3.open(normal);
  await screen.getByRole("button",{name:/^Blue\b/}).waitFor();
  await screen.getByRole("textbox").tap();
  await paste(1,"custom-");
  await browser.locator('button[aria-label="Preview custom-1.png"]:enabled').waitFor();
  await app.screenshot("image-only-before-blue");
  await screen.getByRole("button",{name:/^Blue\b/}).tap();
  await screen.getByRole("button",{name:/^Blue\b/}).waitFor({state:"hidden"});
  await screen.getByText(/^Color: Blue; (?:no )?image received$/).waitFor();
  await app.screenshot("image-only-after-blue");
  const preserved = await browser.locator('[data-chat-composer-form="true"] button[aria-label="Preview custom-1.png"]').isVisible();
  expect({refused,retained,customRetained,preserved}).toEqual({refused:true,retained:true,customRetained:true,preserved:true});
});
