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";

const ACP = `
import { createInterface } from 'node:readline';
import { spawnSync } from 'node:child_process';
const sessionId = 'shell-citation';
const send = x => process.stdout.write(JSON.stringify({jsonrpc:'2.0',...x})+'\\n');
const update = update => send({method:'session/update',params:{sessionId,update}});
for await (const line of createInterface({input:process.stdin})) {
 const {id,method}=JSON.parse(line);
 if(id===undefined)continue;
 if(method==='initialize')send({id,result:{protocolVersion:1,agentCapabilities:{},authMethods:[]}});
 else if(method==='session/new')send({id,result:{sessionId}});
 else if(method==='session/prompt'){
  update({sessionUpdate:'tool_call',toolCallId:'shell',kind:'execute',title:'sh "cd /tmp/factory-pr-42305-evidence-1/probe"',status:'in_progress',rawInput:{command:'sh "cd /tmp/factory-pr-42305-evidence-1/probe"'}});
  const result=spawnSync('sh',['cd /tmp/factory-pr-42305-evidence-1/probe'],{encoding:'utf8'});
  update({sessionUpdate:'tool_call_update',toolCallId:'shell',status:'completed',rawOutput:result.stderr});
  update({sessionUpdate:'agent_message_chunk',content:{type:'text',text:'The shell failed to open its script filename. See :codex-file-citation{path="probe.txt" line_range_start="1"}.'}});
  send({id,result:{stopReason:'end_turn'}});
 }else send({id,result:{}});
}
`;

test('A shell script filename does not become a citation search root', WEB, async ({t3,app,screen,browser})=>{
 await fs.mkdir('/tmp/factory-pr-42305-evidence-1/probe',{recursive:true});
 await fs.writeFile('/tmp/factory-pr-42305-evidence-1/probe/probe.txt','UNRELATED FILE: this folder was never entered by the shell.\n');
 const project=await t3.project('Shell citation demo');
 const script=path.join(T3_HOME,'shell-citation-agent.mjs');
 await fs.writeFile(script,ACP);
 const settingsPath=path.join(T3_HOME,'userdata/settings.json');
 const original=await fs.readFile(settingsPath,'utf8');
 const settings=JSON.parse(original);
 settings.providerInstances['shell-citation-replay']={driver:'acpRegistry',displayName:'Shell citation replay',enabled:true,config:{source:'local',commandPath:process.execPath,commandArgs:[script]}};
 try{
  await fs.writeFile(settingsPath,JSON.stringify(settings));
  const {cli}=makeState(T3_HOME);
  let threadId;
  for(let i=0;i<8 && !threadId;i++){
   const started=await runPromise(cli(['thread','start',project,'Execute exactly sh "cd /tmp/factory-pr-42305-evidence-1/probe" without wrapping it in another shell, then cite probe.txt.','--title','Shell script filename citation','--provider','shell-citation-replay','--model','default','--wait','--json'],[0,1]));
   if(started.stdout.includes('threadId'))threadId=JSON.parse(started.stdout).threadId;
  }
  if(!threadId)throw new Error('Could not start replay agent');
  await t3.open({threadId});
  await screen.getByRole('link',/^probe\.txt/).tap();
  try {
   await expect(browser.locator('[data-right-panel-surface-content]').getByText('The file could not be accessed or read. It may be missing or inaccessible.')).toBeVisible();
  }finally{await app.screenshot('shell-script-citation');}
 }finally{await fs.writeFile(settingsPath,original);}
});
