import * as fs from 'node:fs';
import {execFileSync} from 'node:child_process';
import * as Effect from 'effect/Effect';
import * as Layer from 'effect/Layer';
import { RpcClient, RpcSerialization } from 'effect/rpc';
import { Socket } from 'effect/socket';
import * as NodeWS from '@effect/platform-node/NodeWS';
import { WsRpcGroup, ORCHESTRATION_PROTOCOL_VERSION, ORCHESTRATION_PROTOCOL_HEADER } from '@t3tools/contracts';
const side=process.argv[2];
const out='/tmp/lead-33512-r1/capture';
const repo='/home/ubuntu/wt/pr-33512'+(side==='base'?'-base':'');
const log=fs.readFileSync(out+'/'+side+'-backend.log','utf8');
const port=Number(/serverPort=(\d+)/.exec(log)[1]);
const origin=`http://127.0.0.1:${port}`;
const auth=execFileSync('node',['apps/server/src/bin.ts','auth','session','issue','--base-dir',out+'/'+side+'-state','--token-only'],{cwd:repo,encoding:'utf8'}).trim().split('\n').at(-1);
const headers={'Authorization':'Bearer '+auth,[ORCHESTRATION_PROTOCOL_HEADER]:String(ORCHESTRATION_PROTOCOL_VERSION),'content-type':'application/json'};
async function req(path,body){ const r=await fetch(origin+path,{headers,method:body?'POST':'GET',...(body?{body:JSON.stringify(body)}:{})});if(!r.ok)throw new Error(path+' '+r.status+' '+await r.text());return r.json(); }
const descriptor=await req('/.well-known/t3/environment');
const {ticket}=await req('/api/auth/websocket-ticket',{});
const projectId='7ca1d3cb-3f10-4bfa-8d2a-000000000001';
const threadId='7ca1d3cb-3f10-4bfa-8d2a-000000000002';
await req('/api/projects/mutate',{type:'project.create',commandId:crypto.randomUUID(),projectId,title:'Composer capture',workspaceRoot:out+'/'+side+'-workspace'});
const program=Effect.scoped(Effect.gen(function*(){
 const layer=RpcClient.layerProtocolSocket().pipe(Layer.provide(Socket.layerWebSocket(`${origin.replace('http','ws')}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`)),Layer.provide(RpcSerialization.layerJson),Layer.provide(NodeWS.layerWebSocketConstructor));
 const context=yield* Layer.build(layer);
 const client=yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(context));
 yield* client['server.updateSettings']({patch:JSON.parse(fs.readFileSync(out+'/'+side+'-settings.json','utf8'))});
 yield* client['orchestration.launchThread']({commandId:crypto.randomUUID(),threadId,projectId,title:'Composer send check',modelSelection:{instanceId:'capture',model:'Capture fixture'},runtimeMode:'full-access',interactionMode:'default',workspaceStrategy:{type:'root'}});
 const projection=yield* client['orchestration.getThreadProjection']({threadId});
 fs.writeFileSync(out+'/'+side+'-fixture.json',JSON.stringify({environmentId:descriptor.environmentId,projectId,threadId,port,metro:side==='base'?8087:8088},null,2));
 console.log('Synthetic project and idle composer thread created for '+side+'.');
}));
await Effect.runPromise(program);
