import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import { expect } from 'e2e';
import { APP_DIR } from '../e2e.config.ts';
import { test, WEB } from './t3.ts';

test('Environment setup eval keeps the live activity program name', WEB, async ({t3, app, screen}) => {
  const agentPath = path.join(APP_DIR, 'apps/server/scripts/dev-replay-agent.ts');
  const fixturePath = path.join(APP_DIR, 'apps/server/scripts/dev-replay/showcase_transcript.ndjson');
  const originalAgent = await fs.readFile(agentPath, 'utf8');
  const originalFixture = await fs.readFile(fixturePath, 'utf8');
  const frames: unknown[] = [];
  const prompt = () => frames.push({type:'expect_outbound',frame:{kind:'request',method:'session/prompt',params:'<any>'}});
  const update = (value: unknown, afterMs = 300) => frames.push({type:'emit_inbound', afterMs, frame:{kind:'notification',method:'session/update',params:{sessionId:'dev-replay-session',update:value}}});
  const end = () => frames.push({type:'emit_inbound',frame:{kind:'response',method:'session/prompt',result:{stopReason:'end_turn'}}});
  prompt(); update({sessionUpdate:'agent_message_chunk',content:{type:'text',text:'Ready for environment setup commands.'}}); end();
  prompt();
  const commands = [
    'cd /path/to/repo && eval "$(fnm env --shell zsh)" && fnm use 26.13.1 && git commit -m "msg"',
    'eval "$(/opt/homebrew/bin/brew shellenv)" && pnpm test',
    'export NODE_ENV=test && pnpm test',
  ];
  commands.forEach((command, index) => {
    update({sessionUpdate:'agent_message_chunk',content:{type:'text',text:`\nCommand ${index + 1}\n`}});
    update({sessionUpdate:'tool_call',toolCallId:`execute-${index}`,kind:'execute',title:command,status:'in_progress',rawInput:{command}});
    update({sessionUpdate:'tool_call_update',toolCallId:`execute-${index}`,status:'completed',rawOutput:'Done'}, 15000);
  });
  update({sessionUpdate:'agent_message_chunk',content:{type:'text',text:'Environment setup replay complete.'}}); end();
  try {
    await fs.writeFile(agentPath, originalAgent.replace(/const MAX_RECORDED_DELAY_MS = [^;]+;/, 'const MAX_RECORDED_DELAY_MS = 15000;'));
    await fs.writeFile(fixturePath, frames.map(frame => JSON.stringify(frame)).join('\n')+'\n');
    const project = await t3.project('env-setup-demo');
    const thread = await t3.thread({project,title:'Environment setup activity',messages:['Prepare the replay'],model:'showcase'});
    await t3.open(thread);
    await screen.getByRole('textbox').fill('Run the three environment setup commands');
    await screen.getByRole('textbox').press('Enter');
    await screen.getByText('Command 1', {exact:false}).waitFor();
    await screen.getByText(/^Running (command|fnm)$/).waitFor();
    await app.screenshot('fnm-env-setup-live');
    await screen.getByText('Command 2', {exact:false}).waitFor({timeout:60000});
    await screen.getByText(/^Running (command|pnpm)$/).waitFor();
    await app.screenshot('brew-env-setup-live');
    await expect(screen.getByText('Running pnpm', {exact:true})).toBeVisible({timeout:1000});
  } finally {
    await fs.writeFile(agentPath, originalAgent);
    await fs.writeFile(fixturePath, originalFixture);
  }
});
