import * as NodePath from "node:path";
import { CommandId, ThreadId, ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

// A deterministic ACP replay: identical synthetic history and an exact check of the
// history actually delivered to the new provider, without calling recovery tools.
const ACP = `
import { createInterface } from "node:readline";
const send = m => process.stdout.write(JSON.stringify({jsonrpc:"2.0",...m})+"\\n");
const sessionId = "plan-session";
let plan = Array.from({length:12},(_,i)=>"## Section "+(i+1)+"\\n"+(i===6?"PURPLE-MARMOT-SENTINEL\\n":"")+("Plugins declare stable capabilities, validate input, isolate execution, and preserve compatibility. ").repeat(22)).join("\\n\\n");
plan = plan.slice(0,26113).padEnd(26113," ");
for await(const line of createInterface({input:process.stdin})) {
 const {id,method,params} = JSON.parse(line);
 if(id===undefined) continue;
 if(method==="initialize") send({id,result:{protocolVersion:1,agentCapabilities:{promptCapabilities:{embeddedContext:true}},authMethods:[],agentInfo:{name:"Handoff replay",version:"1"}}});
 else if(method==="session/new") send({id,result:{sessionId,models:{currentModelId:"default",availableModels:[{modelId:"default",name:"Handoff replay"}]}}});
 else if(method==="session/prompt") {
  const update = update => send({method:"session/update",params:{sessionId,update}});
  const message = text => update({sessionUpdate:"agent_message_chunk",content:{type:"text",text}});
  if(process.argv[2]==="source") {
   message("I will inspect the project and write the plugin system plan.\\n");
   for(const [i,command,size] of [[1,"ls",163],[2,"git log --oneline -5",498],[3,"wc -l package.json",74],[4,"cat architecture.md",24000],[5,"cat plugin-notes.md",35000]]) {
    update({sessionUpdate:"tool_call",toolCallId:String(i),kind:"execute",title:command,status:"in_progress",rawInput:{command}});
    update({sessionUpdate:"tool_call_update",toolCallId:String(i),status:"completed",rawOutput:("Synthetic command output. ").repeat(Math.ceil(size/26)).slice(0,size)});
   }
   message(plan);
  } else {
   const texts=[];
   const walk=x=>{if(typeof x==="string") texts.push(x);else if(Array.isArray(x))x.forEach(walk);else if(x&&typeof x==="object")Object.values(x).forEach(walk)};
   walk(params);
   const intact=texts.some(text=>text.includes(plan.trimEnd()));
   message(intact?"HANDOFF RESULT: Plan received intact (26,113 bytes). Section 7 contains PURPLE-MARMOT-SENTINEL. All 12 sections are available for review.":"HANDOFF RESULT: Plan omitted. The new provider did not receive the complete 26,113-byte assistant plan. Recovery would require reading the source thread.");
  }
  send({id,result:{stopReason:"end_turn"}});
 } else send({id,result:{}});
}
`;

test("A 26 KB assistant plan reaches a fresh provider intact", WEB, async ({t3,app,browser,screen})=>{
 const project=await t3.project("handoff-demo",{"handoff-replay.mjs":ACP});
 await runPromise(Effect.gen(function*(){
  const client=yield* rpcClient(T3_HOME,app.baseUrl??"");
  for(const role of ["source","target"]) yield* client["server.updateSettings"]({patch:{},providerInstanceMutation:{operation:"upsert",instanceId:ProviderInstanceId.make("handoff-"+role),instance:{driver:ProviderDriverKind.make("acpRegistry"),displayName:role==="source"?"Plan replay":"Review replay",enabled:true,config:{source:"local",commandPath:process.execPath,commandArgs:[NodePath.join(project,"handoff-replay.mjs"),role]}}}});
 }).pipe(Effect.scoped));
 const {cli}=makeState(T3_HOME);
 const started=await runPromise(cli(["thread","start",project,"Run ls, git log --oneline -5 and wc -l package.json, then write a long 12-section plugin-system plan with the marker in section 7.","--title","Plugin system handoff","--provider","handoff-source","--model","default","--wait","--json"]));
 const thread=JSON.parse(started.stdout) as {threadId:string};
 await t3.open(thread);
 await runPromise(Effect.gen(function*(){
  const client=yield* rpcClient(T3_HOME,app.baseUrl??"");
  yield* client["orchestration.dispatchCommand"]({type:"thread.model-selection.set",commandId:CommandId.make(crypto.randomUUID()),threadId:ThreadId.make(thread.threadId),modelSelection:{instanceId:ProviderInstanceId.make("handoff-target"),model:"default"}});
 }).pipe(Effect.scoped));
 await screen.getByRole("textbox").fill("Review this plan");
 await screen.getByRole("textbox").press("Enter");
 await screen.getByText("HANDOFF RESULT:",{exact:false}).waitFor({timeout:60000});
 await app.screenshot("handoff-result");
 await expect(screen.getByText("HANDOFF RESULT: Plan received intact",{exact:false})).toBeVisible();
});
