/// <reference lib="dom" />
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';

const cases = [
  ['python-attached', "python3 -c'print(1)'"],
  ['perl-repeated', "perl -e'print 1;' -E 'say 2'"],
  ['ruby-bundled', "ruby -0e'puts 42'"],
  ['ruby-repeated', "ruby -e'puts 1' -e 'puts 2'"],
  ['perl-repeated-separated', "perl -e 'print 1;' -E 'say 2'"],
  ['ruby-repeated-separated', "ruby -e 'puts 1' -e 'puts 2'"],
  ['python-option-value', "python3 -uX -c 'print(42)'"],
  ['perl-option-value', "perl -nwI -e 'print 1'"],
  ['ruby-option-value', "ruby -wI -e 'puts 42'"],
  ['python-bundled-option', "python3 -uXdev -c'print(42)'"],
  ['python-bare-heredoc', "python3 -c <<'EOF'\nprint(2)\nEOF"],
  ['psql-bare-heredoc', "psql -c <<'EOF'\nselect 1;\nEOF"],
] as const;

test('Attached scripts and interpreter option boundaries render correctly', WEB, async ({t3,app,screen,browser}) => {
  const project = await t3.project('inline-scripts');
  const fixture = path.join(APP_DIR, 'apps/server/scripts/dev-replay/command_output_transcript.ndjson');
  const original = await fs.readFile(fixture,'utf8');
  const observed: Array<{label:string; spans:Array<{text:string;color:string}>}> = [];
  try {
    for (const [label, command] of cases) {
      const update = (value:object) => ({type:'emit_inbound',frame:{kind:'notification',method:'session/update',params:{sessionId:'dev-replay-session',update:value}}});
      const entries = [
        {type:'expect_outbound',frame:{kind:'request',method:'session/prompt',params:'<any>'}},
        update({sessionUpdate:'tool_call',toolCallId:label,kind:'execute',title:command,status:'in_progress',rawInput:{command}}),
        update({sessionUpdate:'tool_call_update',toolCallId:label,status:'completed',rawOutput:''}),
        update({sessionUpdate:'agent_message_chunk',content:{type:'text',text:'Command display ready.'}}),
        {type:'emit_inbound',frame:{kind:'response',method:'session/prompt',result:{stopReason:'end_turn'}}},
      ];
      await fs.writeFile(fixture, entries.map(x=>JSON.stringify(x)).join('\n')+'\n');
      const thread = await t3.thread({project,title:label,messages:[`Display ${command}`],model:'command-output'});
      await t3.open(thread);
      await screen.getByText('Command display ready.',{exact:true}).waitFor();
      await screen.getByRole('button','Worked for',{exact:false}).tap();
      await screen.getByRole('region','Activity').getByRole('button',command.split('\n')[0],{exact:false}).first().tap();
      await browser.locator('[aria-label="Activity"] span[style*="color"]').first().waitFor();
      const spans = await browser.evaluate(() => [...document.querySelectorAll('[aria-label="Activity"] span[style*="color"]')].map(x=>({text:x.textContent??'',color:getComputedStyle(x).color})));
      observed.push({label,spans});
      await app.screenshot(label);
    }
    console.log(JSON.stringify(observed));
    // The attached Python body must have Python punctuation/number colors rather than one shell string.
    expect(observed[0].spans.some(x=>x.text==='1')).toBe(true);
  } finally { await fs.writeFile(fixture, original); }
});
