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

test('Long live announcements omit the entire cut combining sequence', WEB, async ({t3, app, browser, screen}) => {
  const fixture = path.join(T3_HOME, 'announcement-transcript.ndjson');
  const settingsPath = path.join(T3_HOME, 'userdata/settings.json');
  const original = await fs.readFile(settingsPath, 'utf8');
  const frames: any[] = [];
  const prompt = () => frames.push({type:'expect_outbound',frame:{kind:'request',method:'session/prompt',params:{}}});
  const update = (update: unknown, afterMs = 250) => frames.push({type:'emit_inbound',afterMs,frame:{kind:'notification',method:'session/update',params:{sessionId:'replay',update}}});
  const message = (text: string) => update({sessionUpdate:'agent_message_chunk',content:{type:'text',text}});
  const end = () => frames.push({type:'emit_inbound',frame:{kind:'response',method:'session/prompt',result:{stopReason:'end_turn'}}});
  prompt(); message('Ready for the announcement reproduction.'); end(); prompt();
  for (const count of [111,106]) {
    const name = 'a'.repeat(count)+'e\u0301z';
    update({sessionUpdate:'tool_call',toolCallId:`edit-${count}`,kind:'edit',title:`Edit ${name}`,status:'in_progress',rawInput:{path:`<workspace>/${name}`},locations:[{path:`<workspace>/${name}`}],content:[{type:'diff',path:`<workspace>/${name}`,oldText:'',newText:'proof'}]},2000);
    for(let i=0;i<3;i++) update({sessionUpdate:'tool_call_update',toolCallId:`edit-${count}`,status:'in_progress'},2000);
    update({sessionUpdate:'tool_call_update',toolCallId:`edit-${count}`,status:'completed'});
  }
  message('a'.repeat(1999)+'e\u0301z');
  update({sessionUpdate:'tool_call',toolCallId:'command',kind:'execute',title:'Run proof command',status:'in_progress',rawInput:{command:'true'}},2000);
  update({sessionUpdate:'tool_call_update',toolCallId:'command',status:'completed'},2000);
  message('Finished.'); end();
  await fs.writeFile(fixture,frames.map(f=>JSON.stringify(f)).join('\n'));
  const agentPath = path.join(T3_HOME, 'announcement-replay.ts');
  const agent = await fs.readFile(path.join(APP_DIR, 'apps/server/scripts/dev-replay-agent.ts'),'utf8');
  await fs.writeFile(agentPath, agent.replace('`${FIXTURES}/multi_turn/registry_transcript.ndjson`', JSON.stringify(fixture)));
  const settings = JSON.parse(original);
  settings.providerInstances.devReplay.config.commandArgs=[agentPath];
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  try {
    const project=await t3.project('proj');
    const thread=await t3.thread({project,title:'Combining mark announcement proof',messages:['Prepare'],model:'multi-turn'});
    await t3.open('/settings/chat');
    await screen.getByRole('combobox','Screen reader announcements').tap();
    await screen.getByRole('option','Everything',{exact:true}).tap();
    await t3.open(thread);
    await screen.getByRole('textbox').waitFor();
    await browser.evaluate(() => {
      const seen: string[]=[];
      (window as any).__announcements=seen;
      new MutationObserver((records)=>{
        for(const record of records){
          const el=record.target instanceof Element ? record.target : record.target.parentElement;
          const live=el?.closest('[aria-live="polite"]');
          const text=live?.textContent?.trim();
          if(text && seen.at(-1)!==text) seen.push(text);
        }
      }).observe(document.body,{subtree:true,childList:true,characterData:true});
      return true;
    });
    await screen.getByRole('textbox').fill('Run the announcement reproduction');
    await screen.getByRole('textbox').press('Enter');
    await screen.getByText('Finished.',{exact:true}).waitFor({timeout:60000});
    const observed=await browser.evaluate(() => {
      const seen=(window as any).__announcements as string[];
      const activity=seen.filter(s=>s.startsWith('Editing '));
      const message=seen.find(s=>s.includes('More in the thread.'))??'';
      const panel=document.createElement('section');
      panel.style.cssText='position:fixed;inset:80px 32px auto 32px;z-index:99999;background:#101820;color:#f4f7fa;border:2px solid #83c5e8;border-radius:12px;padding:24px;font:18px/1.6 monospace;box-shadow:0 8px 50px #000';
      const title=document.createElement('h2');title.textContent='Observed app aria-live output';panel.append(title);
      const rows=[...activity.map(s=>`Activity: ${Array.from(s).length} code points; tail ${JSON.stringify(s.slice(-16))}; e before ellipsis: ${s.endsWith('e…')}`),`Message: ${Array.from(message).length} code points; tail ${JSON.stringify(message.slice(-35))}; bare e before suffix: ${message.includes('e More in the thread.')}`,`Source: MutationObserver on the real polite live regions.`, `Expected: the cut e + U+0301 sequence is omitted together.`];
      for(const text of rows){const p=document.createElement('p');p.textContent=text;panel.append(p);}document.body.append(panel);
      return {activity,message};
    });
    await app.screenshot('observed-live-region-cutoffs');
    expect(observed.activity.length).toBe(2);
    expect(observed.activity[1]).toBe('Editing proj/'+'a'.repeat(106)+'…');
    expect(observed.message).toBe('T3 Code: '+'a'.repeat(1999)+' More in the thread.');
  } finally {await fs.writeFile(settingsPath,original);}
});
