import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import { expect } from 'e2e';
import { T3_HOME } from '../e2e.config.ts';
import { makeState, runPromise, test, WEB } from './t3.ts';

test('Failed MCP-over-ACP disconnect can be retried',WEB,async({t3,app,screen})=>{
 const rootBase=process.env.ACP_PROOF_ROOT!;
 const root=await fs.mkdtemp(path.join(rootBase,'run-'));
 await fs.writeFile(path.join(rootBase,'active-run'),root);
 const settingsPath=path.join(T3_HOME,'userdata/settings.json');
 const settings=JSON.parse(await fs.readFile(settingsPath,'utf8'));
 settings.providerInstances.disconnectProof={driver:'acpRegistry',displayName:'Disconnect proof',enabled:true,config:{source:'local',commandPath:process.execPath,commandArgs:[path.join(rootBase,'agent.mjs')],customModels:['proof']}};
 await fs.writeFile(settingsPath,JSON.stringify(settings));
 const project=await t3.project('disconnect-demo');
 const {cli}=makeState(T3_HOME);
 let started='';
 await expect.poll(async()=>{const r=await runPromise(cli(['thread','start',project,'Run the MCP disconnect retry reproduction.','--title','MCP disconnect retry','--provider','disconnectProof','--model','proof','--json'],[0,1])).catch(()=>undefined);if(r?.stdout.includes('threadId'))started=r.stdout;return !!started;},{timeout:60000}).toBe(true);
 await t3.open(JSON.parse(started));
 await expect(screen.getByText('Ready to run disconnect reproduction.')).toBeVisible({timeout:60000});
 await fs.writeFile(path.join(root,'go'),'');
 await expect(screen.getByText('tools/list while DELETE pending: REFUSED')).toBeVisible({timeout:60000});
 await app.screenshot('pending-disconnect');
 await fs.writeFile(path.join(root,'release'),'');
 await expect(screen.getByText('RESULT:',{exact:false})).toBeVisible({timeout:60000});
 await expect.poll(async()=>{const shown=await runPromise(cli(['thread','show',JSON.parse(started).threadId,'--json']));return JSON.parse(shown.stdout).thread.status;},{timeout:60000}).toBe('completed');
 await app.screenshot('disconnect-retry');
 const result=JSON.parse(await fs.readFile(path.join(root,'result.json'),'utf8'));
 await expect(result).toMatchObject({duringRefused:true,retryOk:true,actual:404,control:404,count:2});
});
