import { readFileSync, writeFileSync, symlinkSync } from 'node:fs';
import { join } from 'node:path';
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 { makeState, rpcClient, runPromise, test, WEB } from './t3.ts';

const text = (value: string, kind = 'agent_message_chunk') => ({ sessionUpdate: kind, messageId: '', content: { type: 'text', text: value } });
const tool = { sessionUpdate: 'tool_call', toolCallId: 'background', title: 'Background permissions check', kind: 'execute', status: 'in_progress', rawInput: { command: 'ls -l' } };
const progress = { sessionUpdate: 'tool_call_update', toolCallId: 'background', status: 'in_progress' };
const done = { ...progress, status: 'completed' };
const prefix = '## Permissions summary\n\nThe config file `a.conf` has mode `0';
const tail = '640` (`-rw-r-----`), the key `b.key` has `0600`, and `c.sh` is `0755`.\n\n**Everything is configured correctly.**';
const subagent = { sessionUpdate: 'tool_call', toolCallId: 'child', name: 'Agent', title: 'Verify permissions', kind: 'other', status: 'in_progress', rawInput: { prompt: 'Verify the synthetic permissions.', description: 'Verify permissions' } };
const cases = [
  { label: 'new-subagent-inline', subagent: true, frames: [{ sessionUpdate: 'state_update', state: 'running' }, text(prefix), subagent, text(tail), { sessionUpdate: 'tool_call_update', toolCallId: 'child', status: 'completed' }, { sessionUpdate: 'state_update', state: 'idle', stopReason: 'end_turn' }], code: '0640' },
  { label: 'existing-tool-inline', frames: [tool, text(prefix), progress, text('6'), done, text('40' + tail.slice(3))], code: '0640' },
  { label: 'new-tool-inline', frames: [text(prefix), tool, text(tail), done], code: '0640' },
  { label: 'new-tool-backtick-fence', frames: [text('## Shell example\n\n```sh\nprintf "first line"\n'), tool, text('printf "second line"\n```\n\nThe script is complete.'), done], code: 'printf "first line"\nprintf "second line"' },
  { label: 'new-tool-tilde-fence', frames: [text('## Shell example\n\n~~~sh\nprintf "first line"\n'), tool, text('printf "second line"\n~~~\n\nThe script is complete.'), done], code: 'printf "first line"\nprintf "second line"' },
  { label: 'existing-tool-reasoning', frames: [tool, text('Checking the key mode `0', 'agent_thought_chunk'), progress, text('640` before continuing.', 'agent_thought_chunk'), done, text('Reasoning check finished.')], code: '0640' },
  { label: 'new-tool-reasoning-fence', frames: [text('```sh\nprintf "first line"\n', 'agent_thought_chunk'), tool, text('printf "second line"\n```', 'agent_thought_chunk'), done, text('Reasoning check finished.')], code: 'printf "first line"\nprintf "second line"' },
  { label: 'user-stream-update', frames: [tool, { sessionUpdate: 'user_message', messageId: '', content: [{ type: 'text', text: 'User stream starts' }] }, progress, { sessionUpdate: 'user_message', messageId: '', content: [{ type: 'text', text: 'User stream starts and continues intact.' }] }, done, text('User stream check finished.')], user: true },
  { label: 'sequential-control', frames: [text("I'll list the files first."), tool, done, text('The listing shows `a.conf` at `0640`.')], control: true, code: '0640' },
];

test('Interleaved ACP tools preserve Markdown and sequential messages stay separate', WEB, async ({ t3, app, screen, browser }) => {
  await browser.setViewport({ width: 1280, height: 1100 });
  const replay = join(APP_DIR, 'apps/server/scripts/dev-replay/showcase_transcript.ndjson');
  const agent = join(APP_DIR, 'apps/server/scripts/dev-replay-agent.ts');
  const original = readFileSync(replay, 'utf8');
  const originalAgent = readFileSync(agent, 'utf8');
  writeFileSync(agent, originalAgent.replace('protocolVersion: 1,', 'protocolVersion: 2,').replace('const REPLAYED_UPDATES = new Set([', 'const REPLAYED_UPDATES = new Set(["user_message", "user_message_chunk", "state_update",'));
  const project = await t3.project('permissions-demo', { 'a.conf': 'synthetic config', 'b.key': 'synthetic key', 'c.sh': 'echo ready' });
  const settingsPath = join(T3_HOME, 'userdata/settings.json');
  const settingsOriginal = readFileSync(settingsPath, 'utf8');
  const settings = JSON.parse(settingsOriginal);
  const executable = join(project, 'claude-agent-acp');
  symlinkSync(process.execPath, executable);
  writeFileSync(settingsPath, JSON.stringify({ ...settings, providerInstances: { ...settings.providerInstances, 'subagent-replay': { driver: 'acpRegistry', enabled: true, displayName: 'Subagent Replay', config: { source: 'local', commandPath: executable, commandArgs: [agent] } } } }));
  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 === 'subagent-replay')), Stream.runHead);
  }).pipe(Effect.scoped));
  const failures: string[] = [];
  try {
    for (const entry of cases) {
      const frames = [
        { type: 'expect_outbound', frame: { kind: 'request', method: 'session/prompt' } },
        ...[{ sessionUpdate: 'user_message', messageId: 'ack', content: [{ type: 'text', text: 'Accepted.' }] }, { sessionUpdate: 'state_update', state: 'running' }, text('Ready to demonstrate interleaving.'), { sessionUpdate: 'state_update', state: 'idle', stopReason: 'end_turn' }].map(update => ({ type: 'emit_inbound', frame: { kind: 'notification', method: 'session/update', params: { sessionId: 'replay', update } } })),
        { type: 'emit_inbound', frame: { kind: 'response', method: 'session/prompt', result: { stopReason: 'end_turn' } } },
        { type: 'expect_outbound', frame: { kind: 'request', method: 'session/prompt' } },
        ...[...(entry.subagent ? [{ sessionUpdate: 'user_message', messageId: 'ack-2', content: [{ type: 'text', text: 'Accepted.' }] }] : []), ...entry.frames].map(update => ({ type: 'emit_inbound', afterMs: 350, frame: { kind: 'notification', method: 'session/update', params: { sessionId: 'replay', update } } })),
        { type: 'emit_inbound', frame: { kind: 'response', method: 'session/prompt', result: { stopReason: 'end_turn' } } },
      ];
      writeFileSync(replay, frames.map(frame => JSON.stringify(frame)).join('\n'));
      const thread = entry.subagent ? JSON.parse((await runPromise(makeState(T3_HOME).cli(['thread', 'start', project, 'Show the permissions report.', '--title', entry.label, '--provider', 'subagent-replay', '--model', 'showcase', '--wait', '--json']))).stdout) : await t3.thread({ project, title: entry.label, model: 'showcase', messages: ['Show the permissions report.'] });
      await t3.open(thread);
      await screen.getByText('Ready to demonstrate interleaving.', { exact: true }).waitFor();
      await screen.getByRole('textbox').fill('Run the permissions check.');
      await screen.getByRole('textbox').press('Enter');
      await screen.getByText(entry.label.includes('reasoning') ? 'Reasoning check finished.' : entry.user ? 'User stream check finished.' : entry.control ? 'The listing shows' : entry.label.includes('fence') ? 'The script is complete.' : 'Everything is configured correctly.', { exact: false }).waitFor();
      await screen.getByRole('button', 'Stop generation').waitFor({ state: 'hidden' });
      await screen.getByText('Syncing messages...', { exact: true }).waitFor({ state: 'hidden' });
      const work = screen.getByRole('button', /^Worked for/);
      if ((await work.count()) > 0) await work.tap();
      if (entry.label.includes('reasoning')) {
        await screen.getByRole('button', /^Ran 1 command/).tap();
        await browser.locator('[data-v2-item-type="reasoning"]').first().waitFor();
        await browser.evaluate(`(() => { for (const row of document.querySelectorAll('[data-v2-item-type="reasoning"]')) { row.querySelector('[role="button"][aria-expanded="false"]')?.click(); } return true; })()`);
        await browser.locator('[data-v2-item-type="reasoning"] [aria-expanded="true"]').first().waitFor();
      }
      await browser.evaluate(`Promise.all([document.fonts.ready, ...document.getAnimations().filter(a => a.effect?.getTiming().iterations !== Infinity).map(a => a.finished.catch(() => undefined))]).then(() => true)`);
      await app.screenshot(entry.label);
      if (entry.subagent) {
        const projected = await browser.evaluate<boolean>(`document.querySelector('[data-v2-item-type="subagent"]') !== null`);
        if (!projected) failures.push(entry.label + ': subagent was not projected');
      }
      const codes = await browser.evaluate<string[]>(`Array.from(document.querySelectorAll('code')).map(e => e.textContent || '')`);
      if (entry.code && !codes.some(value => value.includes(entry.code!))) failures.push(entry.label + ': no intact code span/block: ' + JSON.stringify(codes));
      if (entry.user) {
        const intact = await browser.evaluate<boolean>(`Array.from(document.querySelectorAll('[data-thread-find-text]')).filter(e => e.textContent.includes('User stream starts')).length === 1`);
        if (!intact) failures.push(entry.label + ': user text was split');
      }
      if (entry.control) {
        const separate = await browser.evaluate<boolean>(`(() => { const els = [...document.querySelectorAll('[data-thread-find-text]')]; return els.some(e => e.textContent.trim() === "I'll list the files first.") && els.some(e => e.textContent.includes('The listing shows') && !e.textContent.includes("I'll list")); })()`);
        if (!separate) failures.push('sequential-control: messages were not separate');
      }
    }
    expect(failures).toEqual([]);
  } finally {
    writeFileSync(replay, original);
    writeFileSync(agent, originalAgent);
    writeFileSync(settingsPath, settingsOriginal);
  }
});
