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('File searches only expand when their inspector has content', WEB, async ({t3,app,screen,browser}) => {
 const fixture = path.join(APP_DIR,'apps/server/scripts/dev-replay/showcase_transcript.ndjson');
 const original = await fs.readFile(fixture,'utf8');
 const entries: unknown[] = [];
 const update = (value: unknown, afterMs?: number) => entries.push({type:'emit_inbound',frame:{kind:'notification',method:'session/update',params:{sessionId:'search-proof',update:value}},...(afterMs ? {afterMs} : {})});
 for (const query of ['FIXME','TODO','needle']) {
  entries.push({type:'expect_outbound',frame:{kind:'request',method:'session/prompt',params:'<any>'}});
  update({sessionUpdate:'tool_call',toolCallId:query,title:'Grep',kind:'search',status:'in_progress',rawInput:{query,...(query==='needle'?{path:'src'}:{})}});
  if(query!=='TODO') update({sessionUpdate:'tool_call_update',toolCallId:query,status:'completed',...(query==='needle'?{rawOutput:'src/a.ts:3:const needle = 1;'}:{})});
  update({sessionUpdate:'agent_message_chunk',content:{type:'text',text:query==='TODO'?'Still searching TODO.':'Search '+query+' finished.'}});
  if(query==='TODO') update({sessionUpdate:'agent_message_chunk',content:{type:'text',text:'Waiting for the search.'}},120000);
  entries.push({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');
 try {
  const project = await t3.project('proj',{'src/a.ts':'\n\nconst needle = 1;\n'});
  const thread = await t3.thread({project,title:'File search details',messages:['search FIXME'],model:'showcase'});
  await t3.open(thread);
  await screen.getByText('Search FIXME finished.',{exact:true}).waitFor();
  await screen.getByRole('button','Worked for',{exact:false}).first().tap();
  const inspect = async (query:string) => { const expandable = await browser.evaluate((q) => {
   const row = [...document.querySelectorAll<HTMLElement>('[data-work-entry-id]')].find(x=>x.getAttribute('aria-label')===`Searched ${q}` || x.textContent?.trim().startsWith(`Searched ${q}`));
   if(!row) throw new Error('Search row not found: '+q);
   const toggle=row.querySelector<HTMLElement>('[aria-expanded]');
   const expandable=!!toggle;
   
   return expandable;
  },query);
   if(expandable) await screen.getByRole('button',`Searched ${query}`,{exact:true}).tap();
   return expandable;
  };
  const completed = await inspect('FIXME');
  await app.screenshot('completed-empty-search');
  await screen.getByRole('textbox').fill('search TODO');
  await screen.getByRole('textbox').press('Enter');
  await screen.getByText('Still searching TODO.',{exact:false}).waitFor();
  await app.screenshot('running-empty-search');
  await screen.getByRole('button','Stop generation').tap();
  await screen.getByRole('button','Stop generation').waitFor({state:'hidden'});
  const worked = screen.getByRole('button','Worked for',{exact:false});
  await worked.last().tap();
  const interrupted = await inspect('TODO');
  await app.screenshot('interrupted-empty-search');
  await screen.getByRole('textbox').fill('search needle');
  await screen.getByRole('textbox').press('Enter');
  await screen.getByText('Search needle finished.',{exact:true}).waitFor();
  await worked.last().tap();
  await screen.getByRole('button','Searched needle in src',{exact:true}).tap();
  await app.screenshot('search-with-results');
  await expect(screen.getByText('const needle = 1;',{exact:false}).first()).toBeVisible();
  expect([completed,interrupted]).toEqual([false,false]);
 } finally { await fs.writeFile(fixture,original); }
});
