/// <reference lib="dom" />
import { expect } from "e2e";
import { readFileSync, writeFileSync } from "node:fs";
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";

test("Copying a list at the nine-digit limit preserves both items", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("list-copy-demo");
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(readFileSync(settingsPath, 'utf8'));
  settings.providerInstances.opencode = { driver: 'opencode', enabled: true };
  writeFileSync(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));
  const start = async (title: string, markdown: string) => {
    const result = await runPromise(makeState(T3_HOME).cli(['thread', 'start', project,
      `Reply with exactly the following two lines, without a code fence, preamble, tools, or any other text:\n${markdown}`,
      '--title', title, '--provider', 'opencode', '--model', 'openai/gpt-6-luna', '--wait', '--json']));
    return JSON.parse(result.stdout) as { threadId: string };
  };
  const original = await start('Original list', '999999999. first\n1. second');
  await t3.open(original);
  await expect(browser.locator('.chat-markdown:not(.user-message-markdown) ol li')).toHaveCount(2);
  await app.screenshot('original-list');
  // Hold the rendered view long enough for the interaction recording to capture it.
  await browser.evaluate(() => new Promise(resolve => setTimeout(() => resolve(null), 2000)));
  await browser.evaluate(() => {
    const list = document.querySelector('.chat-markdown:not(.user-message-markdown) ol');
    const items = list?.querySelectorAll('li');
    if (!items || items.length !== 2) throw new Error('Original two-item list missing');
    const range = document.createRange();
    range.setStart(items[0].firstChild!, 0);
    range.setEnd(items[1].firstChild!, items[1].firstChild!.textContent!.length);
    window.getSelection()?.removeAllRanges();
    window.getSelection()?.addRange(range);
    document.addEventListener('copy', (event) => {
      queueMicrotask(() => { (window as unknown as { copiedList: string }).copiedList = event.clipboardData?.getData('text/plain') ?? ''; });
    }, { once: true });
    return null;
  });
  await browser.keyboard.press('ControlOrMeta+C');
  const copied = await browser.evaluate(() => (window as unknown as { copiedList: string }).copiedList);
  if (!copied) throw new Error('Copy produced no plain text');
  const roundtrip = await start("Copied plain-text Markdown", copied);
  await t3.open(roundtrip);

  await expect(browser.locator('.chat-markdown:not(.user-message-markdown) ol')).toBeVisible();
  await app.screenshot('copied-markdown-rendered');
  await browser.evaluate(() => new Promise(resolve => setTimeout(() => resolve(null), 2000)));
  await expect(browser.locator('.chat-markdown:not(.user-message-markdown) ol li')).toHaveCount(2);
  await expect(browser.locator('.chat-markdown:not(.user-message-markdown) ol')).toHaveAttribute('start', '999999999');
});
