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 { test, WEB } from "./t3.ts";

// An ACP wire observer: replies report the actual first prompt block, without simulating skills.
const OBSERVER = `
import { createInterface } from 'node:readline';
const send = x => process.stdout.write(JSON.stringify({jsonrpc:'2.0',...x})+'\\n');
for await (const line of createInterface({input:process.stdin})) {
 const {id,method,params={}}=JSON.parse(line);
 if(id===undefined) continue;
 let result={};
 if(method==='initialize') result={protocolVersion:1,agentCapabilities:{promptCapabilities:{embeddedContext:true}},authMethods:[],agentInfo:{name:'Prompt observer',version:'1'}};
 if(method==='session/new') result={sessionId:'observer',models:{currentModelId:'observe',availableModels:[{modelId:'observe',name:'Prompt observer'}]}};
 if(method==='session/prompt') {
  const text=params.prompt.filter(p=>p.type==='text').map(p=>p.text).join('\\n');
  const command=text.includes('/implement do X');
  const continued=text.includes('Continue');
  const history=text.includes('CONTEXT_SENTINEL');
  const reply=text.includes('/project/file.txt do X') ? 'Path prompt received. Handoff history present: '+(history?'YES':'NO')+'.' : command && !continued
   ? 'Slash prompt received. Command at start: '+(text.startsWith('/implement do X')?'YES':'NO')+'. Handoff history in slash prompt: '+(history?'YES':'NO')+'.'
   : 'Continue prompt received. Deferred handoff history present: '+(history?'YES':'NO')+'.';
  send({method:'session/update',params:{sessionId:params.sessionId,update:{sessionUpdate:'agent_message_chunk',content:{type:'text',text:reply}}}});
  result={stopReason:'end_turn'};
 }
 send({id,result});
}
`;

test('Slash command stays first and handoff history waits for Continue', WEB, async ({t3,app,screen,browser}) => {
 const project=await t3.project('demo');
 const thread=await t3.thread({project,title:'Slash command with pending history',messages:['CONTEXT_SENTINEL: preserve this history after the provider switch.']});
 const pathThread=await t3.thread({project,title:'Path with pending history',messages:['CONTEXT_SENTINEL: preserve this history for the path message.']});
 const script=path.join(T3_HOME,'bin/prompt-observer.mjs');
 await fs.writeFile(script,OBSERVER);
 const settingsPath=path.join(T3_HOME,'userdata/settings.json');
 const settings=JSON.parse(await fs.readFile(settingsPath,'utf8'));
 settings.providerInstances.promptObserver={driver:'acpRegistry',enabled:true,displayName:'Prompt observer',config:{source:'local',commandPath:process.execPath,commandArgs:[script]}};
 await fs.writeFile(settingsPath,JSON.stringify(settings));
 await t3.open(thread);
 await browser.locator('[data-chat-provider-model-picker-label]').first().tap();
 await browser.keyboard.type('Prompt observer');
 await screen.getByRole('option', /^Prompt observer/).tap();
 const composer=screen.getByRole('textbox');
 await composer.fill('/implement do X');
 await composer.press('Escape');
 await composer.press('Enter');
 await screen.getByText('Slash prompt received.',{exact:false}).waitFor({timeout:60000});
 await screen.getByRole('button','Stop generation').waitFor({state:'hidden',timeout:60000});
 await app.screenshot('slash-command');
 await composer.fill('Continue');
 await composer.press('Enter');
 await screen.getByText('Continue prompt received.',{exact:false}).waitFor({timeout:60000});
 await screen.getByRole('button','Stop generation').waitFor({state:'hidden',timeout:60000});
 await app.screenshot('deferred-history');
 await t3.open(pathThread);
 await browser.locator('[data-chat-provider-model-picker-label]').first().tap();
 await browser.keyboard.type('Prompt observer');
 await screen.getByRole('option', /^Prompt observer/).tap();
 await composer.fill('/project/file.txt do X');
 await composer.press('Escape');
 await composer.press('Enter');
 await screen.getByText('Path prompt received.',{exact:false}).waitFor({timeout:60000});
 await screen.getByRole('button','Stop generation').waitFor({state:'hidden',timeout:60000});
 await app.screenshot('path-context');
 await expect(screen.getByText('Path prompt received. Handoff history present: YES.',{exact:true})).toBeVisible();
 await t3.open(thread);
 await expect(screen.getByText('Slash prompt received. Command at start: YES. Handoff history in slash prompt: NO.',{exact:true})).toBeVisible();
 await expect(screen.getByText('Continue prompt received. Deferred handoff history present: YES.',{exact:true})).toBeVisible();
});
