import * as NodePath from "node:path";
import { CommandId, ProviderDriverKind, ProviderInstanceId, ThreadId } 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";

const ACP = `
import { createInterface } from 'node:readline';
const sessionId = 'handoff-destination';
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;
 if(method==='initialize') send({id,result:{protocolVersion:1,agentCapabilities:{},authMethods:[],agentInfo:{name:'ACP without native resume',version:'1.0.0'}}});
 else if(method==='session/new') send({id,result:{sessionId}});
 else if(method==='session/prompt') {
  const text=JSON.stringify(params.prompt);
  const ok=text.includes('Continue where you left off.') && text.includes('ocean');
  send({method:'session/update',params:{sessionId,update:{sessionUpdate:'agent_message_chunk',content:{type:'text',text:ok?'Context received. Continuing where we left off.':'Missing continuation prompt or ocean context.'}}}});
  send({id,result:{stopReason:'end_turn'}});
 } else send({id,error:{code:-32601,message:'Method not found'}});
}
`;

test('Resume delivers pending cross-provider context to ACP without native resume', WEB, async ({t3, app, screen, browser}) => {
 const project=await t3.project('ocean-context', {'destination.mjs':ACP});
 const instanceId=ProviderInstanceId.make('handoff-acp');
 await runPromise(Effect.gen(function*(){
  const client=yield* rpcClient(T3_HOME, app.baseUrl ?? '');
  yield* client['server.updateSettings']({patch:{},providerInstanceMutation:{operation:'upsert',instanceId,instance:{driver:ProviderDriverKind.make('acpRegistry'),displayName:'ACP without native resume',enabled:true,config:{source:'local',commandPath:process.execPath,commandArgs:[NodePath.join(project,'destination.mjs')]}}}});
 }).pipe(Effect.scoped));
 await runPromise(Effect.gen(function*(){
  const client=yield* rpcClient(T3_HOME, app.baseUrl ?? '');
  yield* client['server.updateSettings']({patch:{},providerInstanceMutation:{operation:'upsert',instanceId:ProviderInstanceId.make('claudeAgent'),instance:{driver:ProviderDriverKind.make('claudeAgent'),displayName:'Claude',enabled:true,config:{}}}});
 }).pipe(Effect.scoped));
 const started=await runPromise(makeState(T3_HOME).cli(['thread','start',project,'Write a numbered list of 300 short facts about the ocean, one per line. Do not use any tools.','--title','Ocean context handoff','--provider','claudeAgent','--model','claude-haiku-5-5','--json']));
 const thread=JSON.parse(started.stdout);

 await t3.open(thread);
 const composer=browser.locator('[data-chat-composer-form="true"]');
 await composer.getByRole('button','Stop generation').tap();
 await screen.getByRole('button','Resume thread').waitFor({timeout:30000});
 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,model:'default'}});
 }).pipe(Effect.scoped));
 await screen.getByText('Context handoff pending', {exact:false}).first().waitFor({timeout:30000});
 await screen.getByRole('button','Resume thread').tap();
 try {
  await expect(screen.getByText('Context received. Continuing where we left off.',{exact:true})).toBeVisible({timeout:30000});
 } finally {
  await app.screenshot('resume-with-context');
 }
});
