// @effect-diagnostics nodeBuiltinImport:off
import * as http from "node:http";
import * as fs from "node:fs";
import * as path from "node:path";
import { CommandId, MessageId, ThreadId, ProviderInstanceId, ProviderDriverKind } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { mcpToolSession } from "../../apps/server/src/mcp/AcpMcpStdioBridge.ts";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

// A gated protocol replay, using Grok's real active-steering adapter. No model or credentials.
const replay = (origin: string) => `#!${process.execPath}
import {createInterface} from 'node:readline';
const origin=${JSON.stringify(origin)};
if(process.argv.includes('--version')){console.log('grok 1.0.41');process.exit(0);}
if(process.argv.includes('inspect')){console.log(JSON.stringify({skills:[]}));process.exit(0);}
if(process.argv.includes('models')){console.log('You are logged in.\\n- grok-build (default)');process.exit(0);}

const sid='queue-order-replay';
const send=m=>process.stdout.write(JSON.stringify({jsonrpc:'2.0',...m})+'\\n');
const update=text=>send({method:'session/update',params:{sessionId:sid,update:{sessionUpdate:'agent_message_chunk',content:{type:'text',text}}}});
const receive=async(kind,text)=>{
 const label=text.includes('/compact')?'/compact':text.match(/\\b(ALPHA|BRAVO|CHARLIE|SENDER)\\b/g)?.at(-1)??'INITIAL';
 const response=await fetch(origin+'/receive',{method:'POST',body:JSON.stringify({kind,label})});
 const {ordinal}=await response.json();
 if(['ALPHA','BRAVO','CHARLIE'].includes(label))update('Provider received #'+ordinal+': **'+label+'**'+(kind==='steer'?' (active steering)':' (new turn)')+'\\n\\n');
 await fetch(origin+'/gate/'+label);
};
const handle=async r=>{
 const p=r.params??{};
 switch(r.method){
 case 'initialize': return {protocolVersion:1,agentInfo:{name:'queue-order-replay',version:'1'},agentCapabilities:{loadSession:true},authMethods:[]};
 case 'session/new': case 'session/load': {
 const server=(p.mcpServers??[]).find(x=>x.name==='t3-code');
 const env=Object.fromEntries((server?.env??[]).map(x=>[x.name,x.value]));
 const endpoint=server?.url??env.T3_ACP_MCP_ENDPOINT;
 const authorization=server?.headers?.find(x=>x.name.toLowerCase()==='authorization')?.value??env.T3_ACP_MCP_AUTHORIZATION;
 if(endpoint&&authorization)await fetch(origin+'/credentials',{method:'POST',body:JSON.stringify({endpoint,authorization})});
 return {sessionId:sid,models:{currentModelId:'grok-build',availableModels:[{modelId:'grok-build',name:'Queue order replay'}]}}; }
 case 'session/prompt': await receive('prompt',(p.prompt??[]).map(x=>x.text??'').join('\\n'));return {stopReason:'end_turn'};
 case '_x.ai/interject': await receive('steer',p.text??'');return {result:{status:'queued'}};
 default:return {};
 }
};
createInterface({input:process.stdin}).on('line',line=>{const r=JSON.parse(line);if(r.id===undefined)return;void handle(r).then(result=>send({id:r.id,result}),e=>send({id:r.id,error:{code:-32603,message:String(e)}}));});
`;

test("Agent auto messages queued behind /compact preserve send order", WEB, async ({t3,app,screen})=>{
 const received: string[]=[];
 const credentials=[] as Array<{endpoint:string;authorization:string}>;
 const arrived=new Map<string, ReturnType<typeof Promise.withResolvers<void>>>();
 const gates=new Map<string, ReturnType<typeof Promise.withResolvers<void>>>();
 for(const label of ['/compact','ALPHA','BRAVO','CHARLIE','SENDER']) arrived.set(label,Promise.withResolvers<void>());
 for(const label of ['/compact','ALPHA','SENDER']) gates.set(label,Promise.withResolvers<void>());
 const control=http.createServer(async(req,res)=>{
  if(req.url==='/credentials'){
   let body='';for await(const chunk of req)body+=chunk;const data=JSON.parse(body);credentials.push(data);res.writeHead(200).end();
  }else if(req.url==='/receive'){
   let body='';for await(const chunk of req)body+=chunk;
   const {label}=JSON.parse(body);
   if(['ALPHA','BRAVO','CHARLIE'].includes(label))received.push(label);
   arrived.get(label)?.resolve();
   res.writeHead(200,{'Content-Type':'application/json'}).end(JSON.stringify({ordinal:received.length}));
  }else if(req.url?.startsWith('/gate/')){
   await gates.get(decodeURIComponent(req.url.slice(6)))?.promise;
   res.writeHead(200).end('released');
  }else res.writeHead(404).end();
 });
 await new Promise<void>(resolve=>control.listen(0,'127.0.0.1',resolve));
 const address=control.address();if(!address||typeof address==='string')throw new Error('No replay control address');
 try{
  const project=await t3.project('queue-order',{ 'queue-replay.mjs':replay(`http://127.0.0.1:${address.port}`)});
  const binaryPath=path.join(project,'queue-replay.mjs');fs.chmodSync(binaryPath,0o755);
  const instanceId=ProviderInstanceId.make('queueReplay');
  const rpc=<A>(f:(client:any)=>Effect.Effect<A,any,any>)=>runPromise(Effect.gen(function*(){const client=yield* rpcClient(T3_HOME,app.baseUrl??'');return yield* f(client);}).pipe(Effect.scoped));
  await rpc(client=>client['server.updateSettings']({patch:{},providerInstanceMutation:{operation:'upsert',instanceId,instance:{driver:ProviderDriverKind.make('grok'),displayName:'Queue order replay',enabled:true,config:{binaryPath}}}}));
  const launched=await runPromise(makeState(T3_HOME).cli(['thread','start',project,'INITIAL','--title','Agent delivery order','--provider','queueReplay','--model','grok-build','--wait','--json']));
  const thread={threadId:JSON.parse(launched.stdout).threadId};
  const threadId=ThreadId.make(thread.threadId);
  const senderResult=await runPromise(makeState(T3_HOME).cli(['thread','start',project,'INITIAL','--title','Sending agent','--provider','queueReplay','--model','grok-build','--wait','--json']));
  const sender=JSON.parse(senderResult.stdout);
  const senderCredentials=credentials.at(-1);if(!senderCredentials)throw new Error('Missing synthetic sender MCP credentials');
  await rpc(client=>client['orchestration.dispatchCommand']({type:'message.dispatch',commandId:CommandId.make(crypto.randomUUID()),threadId:ThreadId.make(sender.threadId),messageId:MessageId.make(crypto.randomUUID()),text:'SENDER',attachments:[],createdBy:'user',creationSource:'web',dispatchMode:{type:'start_immediately'}}));
  await arrived.get('SENDER')!.promise;
  for(let n=0;n<100;n++){
   const p:any=await rpc(client=>client['orchestration.getThreadProjection']({threadId:ThreadId.make(sender.threadId)}));
   if(p.providerTurns.some((turn:any)=>turn.status==='running'))break;
   await new Promise(resolve=>setTimeout(resolve,50));
  }
  await t3.open(thread);
  await screen.getByRole('heading','Agent delivery order').waitFor();
  const dispatch=async(text:string,agent=false)=>rpc(client=>client['orchestration.dispatchCommand']({type:'message.dispatch',commandId:CommandId.make(crypto.randomUUID()),threadId,messageId:MessageId.make(crypto.randomUUID()),text,attachments:[],createdBy:agent?'agent':'user',creationSource:agent?'mcp':'web',...(agent?{senderThreadId:ThreadId.make(sender.threadId),deliveryIntent:'auto'}:{}),dispatchMode:{type:'start_immediately'}}));
  const send=async(message:string)=>runPromise(Effect.gen(function*(){
   const session=yield* mcpToolSession({...senderCredentials!,clientName:'queue-order-replay'});
   const result:any=yield* session.call('t3_thread_send',{threadId:thread.threadId,message,mode:'auto'});
   if(result.isError)throw new Error(JSON.stringify(result));
  }).pipe(Effect.scoped));
  await dispatch('/compact');
  await arrived.get('/compact')!.promise;
  await send('ALPHA');
  await send('BRAVO');
  await screen.getByText('BRAVO',{exact:false}).first().waitFor();
  await app.screenshot('queued-during-compact');
  gates.get('/compact')!.resolve();
  await arrived.get('ALPHA')!.promise;
  await screen.getByText('Provider received #1:',{exact:false}).waitFor();
  await send('CHARLIE');
  // Wait for either steering delivery or the persisted queued run, before releasing ALPHA.
  for(let n=0;n<100;n++){
   const p:any=await rpc(client=>client['orchestration.getThreadProjection']({threadId}));
   const message=p.messages.find((m:any)=>m.text==='CHARLIE');
   if(received.includes('CHARLIE')||p.runs.some((r:any)=>r.userMessageId===message?.id&&r.status==='queued'))break;
   await new Promise(resolve=>setTimeout(resolve,50));
  }
  await app.screenshot('charlie-sent-while-alpha-running');
  gates.get('ALPHA')!.resolve();
  await arrived.get('BRAVO')!.promise;
  await arrived.get('CHARLIE')!.promise;
  await screen.getByText('Provider received #3:',{exact:false}).waitFor();
  await screen.getByRole('button','Stop generation').waitFor({state:'hidden'});
  await app.screenshot('provider-delivery-order');
  expect(received,'Provider must receive agent messages in send order').toEqual(['ALPHA','BRAVO','CHARLIE']);
 }finally{
  for(const gate of gates.values())gate.resolve();
  control.close();control.closeAllConnections();
 }
});
