import {readFile,writeFile} from 'node:fs/promises';
import {CommandId,ProviderInstanceId,ThreadId} from '@t3tools/contracts';
import * as Effect from 'effect/Effect';
import {environmentId,makeState,rpcClient,runPromise} from './scenarios/t3.ts';
const [side,action]=process.argv.slice(2);
const root=process.env.EVIDENCE_DIR;
if(!root) throw new Error('Set EVIDENCE_DIR to the synthetic capture directory');
const home=`${root}/${side}-primary`;
const home2=`${root}/${side}-secondary`;
const origin='http://127.0.0.1:7933',host='http://127.0.0.1:7935';
const withRpc=(h:string,url:string,use:(client:any)=>any)=>runPromise(Effect.flatMap(rpcClient(h,url),use).pipe(Effect.scoped));
const claude=async(enabled:boolean)=>{
 const settings=JSON.parse(await readFile(`${home}/userdata/settings.json`,'utf8'));
 await withRpc(home,origin,c=>c['server.updateSettings']({patch:{providerInstances:{...settings.providerInstances,claudeAgent:{driver:'claudeAgent',enabled,config:{}}}}}));
};
if(action==='disable'||action==='enable'){await claude(action==='enable');console.log(action);}
if(action==='seed'){
 const first=makeState(home),second=makeState(home2);
 const project=await first.state.project('Sending indicators');
 const remoteProject=await second.state.project('Other environment');
 await claude(true);
 const out=await runPromise(first.cli(['thread','start',project,'/goal Reply exactly GOAL_READY','--title','Chat A — goal','--provider','claudeAgent','--model','claude-haiku-5-5','--wait','--json'],[0,2]));
 const a=JSON.parse(out.stdout);
 const b=await first.state.thread({project,title:'Chat B — pending send',messages:['First'],model:'multi-turn'});
 const create=async(h:string,url:string,path:string,title:string)=>withRpc(h,url,c=>Effect.gen(function*(){
   const {projects}=yield* c['orchestration.getArchivedShellSnapshot']({});
   const projectId=projects.find((p:any)=>p.workspaceRoot===path).id;
   yield* c['orchestration.dispatchCommand']({type:'thread.create',commandId:CommandId.make(`create:${title}`),threadId:ThreadId.make('same-thread-id'),projectId,title,createdBy:'user',creationSource:'web',modelSelection:{instanceId:ProviderInstanceId.make('devReplay'),model:'multi-turn'},runtimeMode:'full-access',interactionMode:'default',branch:null,worktreePath:null});
 }));
 await create(home,origin,project,'Environment one — pending send');
 await create(home2,host,remoteProject,'Environment two — idle');
 const data={a:a.threadId,b:b.threadId,c:'same-thread-id',d:'same-thread-id',env:await runPromise(environmentId(origin)),remoteEnv:await runPromise(environmentId(host))};
 await writeFile(`${root}/${side}-ids.json`,JSON.stringify(data));
 console.log(JSON.stringify(data));
}
