/// <reference lib="dom" />
import * as fs from "node:fs";
import * as path from "node:path";
import { CommandId, ThreadId, ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
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("Assistant citations retain dot-segment thread IDs", WEB, async ({ t3, app, browser, screen }) => {
  const tap = `import { spawn } from 'node:child_process';
import { appendFileSync } from 'node:fs';
const child = spawn(process.execPath, [process.argv[2]], { stdio: ['pipe', 'pipe', 'inherit'] });
let buffer = '';
process.stdin.on('data', data => {
  buffer += data.toString();
  let i;
  while ((i = buffer.indexOf('\\n')) >= 0) {
    const line = buffer.slice(0, i); buffer = buffer.slice(i + 1);
    try { const message = JSON.parse(line); if (message.method === 'session/prompt') appendFileSync(process.argv[3], JSON.stringify(message.params) + '\\n'); } catch {}
  }
});
process.stdin.pipe(child.stdin); child.stdout.pipe(process.stdout);
process.stdin.on('end', () => child.stdin.end());
process.on('SIGTERM', () => child.kill('SIGTERM'));
child.on('exit', code => process.exit(code ?? 0));
`;
  const project = await t3.project("citation-demo", { "replay-tap.mjs": tap });
  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 === "command-output"));
    }), Stream.runHead);
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const control = await t3.thread({ project, title: "Control thread", model: "command-output", messages: ["Run the command"] });
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    const source = yield* client["orchestration.getThreadProjection"]({ threadId: ThreadId.make(control.threadId) });
    yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: {
      operation: "upsert", instanceId: ProviderInstanceId.make("citationReplay"), instance: {
        driver: ProviderDriverKind.make("acpRegistry"), displayName: "Replay citation capture", enabled: true,
        config: { source: "local", commandPath: process.execPath, commandArgs: [path.join(project, "replay-tap.mjs"), path.join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts"), path.join(project, "prompts.ndjson")] },
      },
    }});
    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 === "citationReplay" && p.models?.some(m => m.slug === "command-output"));
    }), Stream.runHead);
    for (const id of [".", ".."]) {
      yield* client["orchestration.launchThread"]({
        commandId: CommandId.make(crypto.randomUUID()), threadId: ThreadId.make(id),
        projectId: source.thread.projectId, title: `Dot thread ${id}`,
        modelSelection: { instanceId: ProviderInstanceId.make("citationReplay"), model: "command-output" }, runtimeMode: "full-access", interactionMode: "default",
        workspaceStrategy: { type: "root" }, initialMessage: { text: "Run the command", attachments: [] },
      });
    }
  }).pipe(Effect.scoped));
  await t3.open(control);
  const results: Array<{ id: string; composerChips: number; savedChips: number }> = [];
  for (const id of [".", ".."]) {
    await browser.locator(`[data-sidebar-row$=":${id}"]`).tap();
    await screen.getByText("The command printed one JSON line.", { exact: true }).waitFor();
    await browser.evaluate(() => {
      const source = document.querySelector('[data-assistant-citation-source]');
      if (!source) throw new Error("Assistant reply missing");
      const paragraph = [...source.querySelectorAll('p')].find(p => p.textContent === "The command printed one JSON line.");
      if (!paragraph) throw new Error("Reply paragraph missing");
      const range = document.createRange(); range.selectNodeContents(paragraph);
      window.getSelection()?.removeAllRanges(); window.getSelection()?.addRange(range);
      document.dispatchEvent(new Event('selectionchange'));
      return null;
    });
    await screen.getByRole("button", "Cite selection in composer", { exact: true }).tap();
    // Save is available only when parsing created the citation chip and its comment editor.
    const hasSave = await browser.evaluate(() => !!document.querySelector('textarea[aria-label="Comment on selected text"]'));
    if (hasSave) await screen.getByRole("button", "Save", { exact: true }).tap();
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().filter(a => a.effect?.getComputedTiming().iterations !== Infinity).map(a => a.finished.catch(() => {})));
      return null;
    });
    await app.screenshot(`dot-${id.length}-composer`);
    const composerChips = await browser.evaluate(() => document.querySelectorAll('[data-chat-composer-form] [data-assistant-citation-chip]').length);
    await browser.locator('[data-chat-composer-form] [role="textbox"]').tap();
    await browser.keyboard.press("Enter");
    await browser.locator('[data-user-message-body]').filter({ hasText: /Assistant quote|The command printed one JSON line/ }).waitFor();
    await browser.evaluate(() => new Promise<void>(resolve => {
      const finished = () => [...document.querySelectorAll('[data-assistant-citation-source] p')].filter(p => p.textContent === "The command printed one JSON line.").length >= 2 && !document.querySelector('button[aria-label="Stop generation"]');
      if (finished()) return resolve();
      const observer = new MutationObserver(() => { if (finished()) { observer.disconnect(); resolve(); } });
      observer.observe(document.body, { subtree: true, childList: true, attributes: true, characterData: true });
    }));
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().filter(a => a.effect?.getComputedTiming().iterations !== Infinity).map(a => a.finished.catch(() => {})));
      return null;
    });
    await app.screenshot(`dot-${id.length}-saved`);
    const savedChips = await browser.evaluate(() => document.querySelectorAll('[data-user-message-body] [data-thread-find-ignore]').length);
    results.push({ id, composerChips, savedChips });
  }
  const prompts = fs.readFileSync(path.join(project, "prompts.ndjson"), "utf8").trim().split("\n").map(line => JSON.parse(line));
  const citationPrompts = prompts.map(p => p.prompt.filter(b => b.type === "text").map(b => b.text).join("\n")).filter(text => text.includes("assistant-quote-1") || text.includes("t3-citation://"));
  const payloads = citationPrompts.map(text => ({
    placeholder: text.includes("[assistant-quote-1]"),
    rawMarker: text.includes("[Assistant quote](t3-citation://"),
    assistantCitations: text.match(/<assistant_citations>([\s\S]*?)<\/assistant_citations>/)?.[1] ?? null,
  }));
  fs.writeFileSync(path.join(process.env.T3_CITATION_PROOF_DIR!, `provider-${APP_DIR.split("-").at(-1)}.json`), JSON.stringify({ results, payloads }, null, 2));
  expect(payloads.map(p => p.placeholder)).toEqual([true, true]);
  expect(payloads.map(p => p.assistantCitations?.match(/"threadId": "([^"]+)"/)?.[1])).toEqual([".", ".."]);
  expect(results).toEqual([{ id: ".", composerChips: 1, savedChips: 1 }, { id: "..", composerChips: 1, savedChips: 1 }]);
});
