import * as FS from "node:fs/promises";
import * as Path from "node:path";
import { randomUUID } from "node:crypto";
import { CommandId, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

// Deterministic ACP replay probe: fail session creation on demand and report the actual
// server-supplied prompt, rather than asking a paid model to infer what context it received.
const AGENT = `
import { existsSync } from 'node:fs';
import { createInterface } from 'node:readline';
import { randomUUID } from 'node:crypto';
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,agentInfo:{name:'context-replay-probe',version:'1'},agentCapabilities:{loadSession:true,promptCapabilities:{embeddedContext:true}},authMethods:[]};
 else if(method==='session/new'||method==='session/load') {
  if(existsSync(process.argv[2])) {send({id,error:{code:-32000,message:'Synthetic provider unavailable before prompt acceptance'}});continue;}
  result={sessionId:params.sessionId??randomUUID(),models:{currentModelId:'multi-turn',availableModels:[{modelId:'multi-turn',name:'Context probe'}]}};
 } else if(method==='session/prompt') {
  const text=JSON.stringify(params.prompt);
  const digest=text.includes('Main thread activity since this side chat');
  const pineapple=text.includes('PINEAPPLE');
  const reply=text.includes('What context')||text.includes('Check again')
    ? (digest ? 'DIGEST RECEIVED: main-thread activity was injected.'+(pineapple?' The codeword is PINEAPPLE.':'') : 'CLEAN SESSION: no main-thread digest was supplied.')
    : 'Recorded the main-thread fact.';
  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('Clear after a failed first side-chat run excludes the waiting main-thread digest', WEB, async ({t3,app,screen}) => {
 const project=await t3.project('context-demo');
 const main=await t3.thread({project,title:'Main thread',messages:['Initial work before the side chat']});
 const side={threadId:randomUUID()};
 const script=Path.join(T3_HOME,'bin/context-probe.mjs');
 const gate=Path.join(T3_HOME,'bin/provider-unavailable');
 await FS.writeFile(script,AGENT);
 const call = <A, E>(fn: (client: Effect.Effect.Success<ReturnType<typeof rpcClient>>) => Effect.Effect<A,E>) => runPromise(Effect.scoped(Effect.gen(function*(){ const client=yield* rpcClient(T3_HOME,app.baseUrl??'');return yield* fn(client);})));
 const settings=JSON.parse(await FS.readFile(Path.join(T3_HOME,'userdata/settings.json'),'utf8'));
 await call(client=>client['server.updateSettings']({patch:{providerInstances:{...settings.providerInstances,devReplay:{driver:'acpRegistry',displayName:'Replay context probe',enabled:true,config:{source:'local',commandPath:process.execPath,commandArgs:[script,gate]}}}}}));
 await call(client=>client['orchestration.dispatchCommand']({type:'thread.fork',commandId:CommandId.make(randomUUID()),sourceThreadId:ThreadId.make(main.threadId),targetThreadId:ThreadId.make(side.threadId),sourcePoint:{type:'latest_stable'},sideChat:true,title:'Side chat',createdBy:'user',creationSource:'web'}));
 await t3.open(main);
 await screen.getByRole('textbox').fill('The codeword is PINEAPPLE. Keep this fact in the main thread.');
 await screen.getByRole('textbox').press('Enter');
 await screen.getByText('second fixture turn complete',{exact:false}).waitFor({timeout:60000});
 await screen.getByRole('button','Stop generation').waitFor({state:'hidden',timeout:60000});
 await app.screenshot('main-fact-after-side-chat-opened');
 await FS.writeFile(gate,'fail session creation');
 await t3.open(side);
 await screen.getByRole('textbox').fill('First side-chat attempt');
 await screen.getByRole('textbox').press('Enter');
 await screen.getByText('The provider needs you to sign in.',{exact:false}).first().waitFor({timeout:60000});
 await app.screenshot('failed-before-prompt-acceptance');
 await FS.unlink(gate);
 await screen.getByRole('textbox').fill('/clear');
 await screen.getByRole('textbox').press('Enter');
 await screen.getByRole('textbox').fill('What context do you have about the main thread?');
 await screen.getByRole('textbox').press('Enter');
 const report=screen.getByText(/CLEAN SESSION:|DIGEST RECEIVED:/).first();
 await report.waitFor({timeout:60000});
 await screen.getByRole('button','Stop generation').waitFor({state:'hidden',timeout:60000});
 await app.screenshot('fresh-session-context');
 await screen.getByRole('textbox').fill('Check again on this later ordinary prompt.');
 await screen.getByRole('textbox').press('Enter');
 await screen.getByRole('button','Stop generation').waitFor({state:'hidden',timeout:60000});
 await screen.getByText(/CLEAN SESSION:|DIGEST RECEIVED:/).nth(1).waitFor({timeout:60000});
 await app.screenshot('later-session-context');
 await expect(screen.getByText('DIGEST RECEIVED:',{exact:false})).toBeHidden();
});
