/// <reference lib="dom" />
import * as fs from 'node:fs/promises';
import { expect } from 'e2e';
import { T3_HOME } from '../e2e.config.ts';
import { makeState, runPromise, test, WEB } from './t3.ts';

const commands = ["python3 -c 'print(1)'", "timeout 30 python3 -c 'print(1)'", "timeout -k 5 30s node -e 'console.log(1)'", "node -e 'console.log(1)'"];
test('Timeout wrapped inline scripts receive embedded language colours', WEB, async ({t3, app, screen, browser}) => {
 const project = await t3.project('inline-scripts');
 const path = `${T3_HOME}/userdata/settings.json`;
 const settings = JSON.parse(await fs.readFile(path,'utf8'));
 settings.providerInstances.opencode = {driver:'opencode', enabled:true, config:{binaryPath:'opencode'}};
 await fs.writeFile(path,JSON.stringify(settings));
 await t3.open();
 const {cli} = makeState(T3_HOME);
 const started = await runPromise(cli(['thread','start',project, 'Run exactly four separate Bash tool calls verbatim, one command per tool call. Do not combine them. Do not inspect files or run other tools. Commands:\n'+commands.join('\n')+'\nThen reply DONE.', '--title','Inline script highlighting','--provider','opencode','--model','anthropic/claude-haiku-5-5','--wait','--json'],[0,2]));
 const {threadId} = JSON.parse(started.stdout);
 await t3.open({threadId});
 await screen.getByRole('button','Worked for',{exact:false}).tap();
 const group = screen.getByRole('button','Ran 4 commands',{exact:false});
 await group.tap();
 for(const command of commands) await screen.getByRole('button',command,{exact:true}).first().tap();
 await browser.locator('div[class="text-foreground/85"] span[style]').last().waitFor();
 await app.screenshot('expanded-inline-scripts');
 const colours = await browser.evaluate(() => [...document.querySelectorAll('div[class="text-foreground/85"]')].filter(p=>p.textContent?.includes('print(1)') || p.textContent?.includes('console.log(1)')).map(p=>{
 const text = p.textContent ?? '';
 const script = text.includes('print(1)') ? 'print(1)' : 'console.log(1)';
 const start = text.indexOf(script), end = start + script.length;
 const walker = document.createTreeWalker(p, NodeFilter.SHOW_TEXT);
 let offset = 0; const colours: string[] = [];
 for(let node = walker.nextNode();node;node=walker.nextNode()) {
  const next = offset + (node.textContent?.length ?? 0);
  if(next > start && offset < end) colours.push(getComputedStyle(node.parentElement!).color);
  offset = next;
 }
 return {text, colours:[...new Set(colours)]};
 }));
 console.log(JSON.stringify(colours));
 expect(colours.filter(p=>p.text.includes('timeout')).map(p=>p.colours.length)).toEqual([3,4]);
});
