import * as fs from "node:fs/promises";
import * as path from "node:path";
import { execFileSync } from "node:child_process";
import { APP_DIR } from "../e2e.config.ts";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";
const ACP = `#!/usr/bin/env node
import { createInterface } from 'node:readline';
const send = m => process.stdout.write(JSON.stringify({jsonrpc:'2.0',...m})+'\\n');
const sessionId = 'usage-proof';
const update = update => send({method:'session/update',params:{sessionId,update}});
for await (const line of createInterface({input:process.stdin})) {
 const {id,method,params} = JSON.parse(line);
 if (id === undefined) continue;
 if (method === 'initialize') send({id,result:{protocolVersion:1,agentInfo:{name:'Usage proof',version:'1'},agentCapabilities:{},authMethods:[]}});
 else if (method === 'session/new') send({id,result:{sessionId}});
 else if (method === 'session/prompt') {
  for (const name of ['a.txt','b.txt']) {
   update({sessionUpdate:'tool_call',toolCallId:name,title:'Read proj/'+name,kind:'read',status:'in_progress',locations:[{path:'proj/'+name}]});
   update({sessionUpdate:'tool_call_update',toolCallId:name,status:'completed',content:[{type:'content',content:{type:'text',text:'Reading '+name}}]});
  }
  send({id,error:{code:-31001,message:'429: Usage limit reached. Retry manually.'}});
 }
 else send({id,result:{}});
}
`;
test('Completed reads stay grouped after a usage-limit pause and reload', WEB, async ({t3,app,screen,browser}) => {
 async function stable(label) {
  let a=await app.screenshot(label+'-settling');
  for(let n=0;n<20;n++) {
   await new Promise(r=>setTimeout(r,500));
   const b=await app.screenshot(label+'-stable');
   if((await fs.readFile(a)).equals(await fs.readFile(b))) return;
   a=b;
  }
  throw Error('Web capture did not settle');
 }
 const project = await t3.project('proj', {'a.txt':'Alpha\n','b.txt':'Beta\n'});
 const script = path.join(project,'vibe-acp');
 await fs.writeFile(script,ACP); await fs.chmod(script,0o755);
 const settingsPath=path.join(T3_HOME,'userdata/settings.json');
 const settings=JSON.parse(await fs.readFile(settingsPath,'utf8'));
 settings.providerInstances['usage-proof']={driver:'acpRegistry',displayName:'Usage proof',enabled:true,config:{source:'local',commandPath:script,commandArgs:[]}};
 await fs.writeFile(settingsPath,JSON.stringify(settings));
 const {cli}=makeState(T3_HOME);
 let threadId;
 for(let n=0;n<8 && !threadId;n++) {
  const started=await runPromise(cli(['thread','start',project,'Read a.txt and b.txt and summarize them.','--title','Usage limit pause','--provider','usage-proof','--model','default','--wait','--json'],[0,1,2]));
  if(started.stdout.includes('threadId')) threadId=JSON.parse(started.stdout).threadId;
 }
 if(!threadId) throw Error('Provider could not start');
 await t3.open({threadId});
 await screen.getByText('Usage limit reached',{exact:true}).waitFor({timeout:60000});
 // Wait for the untracked synthetic provider to be reflected in repository status.
 await screen.getByText('+19',{exact:true}).first().waitFor({timeout:60000});
 await stable('usage-limit-paused');
 await browser.reload();
 await screen.getByText('Usage limit reached',{exact:true}).waitFor({timeout:60000});
 await screen.getByText('+19',{exact:true}).first().waitFor({timeout:60000});
 await stable('usage-limit-after-reload');
 await expect(screen.getByRole('button',/Read 2 files/)).toBeVisible();
});
