import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeWS from "@effect/platform-node/NodeWS";
import {WsRpcGroup,ORCHESTRATION_PROTOCOL_VERSION} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { RpcClient, RpcSerialization } from "effect/rpc";
import {Socket} from "effect/socket";
import {spawnSync} from "node:child_process";
import {readFileSync,appendFileSync, mkdirSync, existsSync} from "node:fs";
import {DatabaseSync} from "node:sqlite";
import {randomUUID as uuid} from "node:crypto";
const [home,origin,out,targetStr="100"] = process.argv.slice(2);
mkdirSync(out,{recursive:true});
const token=spawnSync(process.execPath,["apps/server/src/bin.ts","auth","session","issue","--token-only","--base-dir",home],{encoding:"utf8",cwd:process.cwd().endsWith("apps/server")?"../..":process.cwd()}).stdout.trim();
if(!token) throw Error("No token");
const {ticket}=await (await fetch(origin+"/api/auth/websocket-ticket",{method:"POST",headers:{authorization:`Bearer ${token}`}})).json();
const db = new DatabaseSync(home+"/userdata/statev2.sqlite",{readOnly:true});
const log=x=>{console.log(JSON.stringify(x));appendFileSync(out+"/driver.ndjson",JSON.stringify(x)+"\n")};
const nap=ms=>new Promise(r=>setTimeout(r,ms));
const latestStmt=db.prepare("SELECT payload_json FROM orchestration_v2_projection_runs WHERE thread_id=? ORDER BY ordinal DESC LIMIT 1");
const latest=id=>{const r=latestStmt.get(id);return r?JSON.parse(r.payload_json):null};
async function wait(id,pred){const deadline=Date.now()+60000;while(Date.now()<deadline){const r=latest(id);if(r&&pred(r))return r;await nap(10)}throw Error("Run wait timed out")}
await Effect.runPromise(Effect.scoped(Effect.gen(function*(){
 const protocol=yield* Layer.build(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 client=yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
 const dispatch=(c)=>Effect.runPromise(client["orchestration.dispatchCommand"]({...c,commandId:uuid()}));
 const req=(method,input)=>Effect.runPromise(client[method](input));
 yield* Effect.tryPromise(async()=>{
 const projectId=uuid(),threadId=uuid();
 const created=await fetch(origin+"/api/projects/mutate",{method:"POST",headers:{authorization:`Bearer ${token}`,"content-type":"application/json"},body:JSON.stringify({type:"project.create",commandId:uuid(),projectId,title:"Turn start performance",workspaceRoot:process.cwd()})});
 if(!created.ok)throw Error(await created.text());
 await dispatch({type:"thread.create",threadId,projectId,title:"Synthetic long thread",modelSelection:{instanceId:"devReplay",model:"bench-stream"},runtimeMode:"full-access",interactionMode:"default",branch:null,worktreePath:null,createdBy:"user",creationSource:"web"});
 const send=async(text)=>{await dispatch({type:"message.dispatch",threadId,messageId:uuid(),text,attachments:[],dispatchMode:{type:"start_immediately"},createdBy:"user",creationSource:"web"});};
 await send("Start the recorded long turn");
 const parent=await wait(threadId,r=>r.status==="running");
 await dispatch({type:"delegated_task.request",parentThreadId:threadId,parentRunId:parent.id,parentNodeId:parent.rootNodeId,task:"Play the recorded long turn",modelSelection:{instanceId:"devReplay",model:"bench-stream"},runtimeMode:"full-access",interactionMode:"default",completionWake:"always",createdBy:"agent",creationSource:"mcp"});
 let projection=await req("orchestration.getThreadProjection",{threadId});
 const task=projection.subagents[0];
 await wait(task.childThreadId,r=>r.status==="running");
 await dispatch({type:"thread.stop",threadId});
 await wait(threadId,r=>["cancelled","interrupted","completed"].includes(r.status));
 await wait(task.childThreadId,r=>["cancelled","interrupted","completed"].includes(r.status));
 await nap(200);
 projection=await req("orchestration.getThreadProjection",{threadId});
 log({stage:"stopped",run:projection.runs[0],task:projection.subagents[0]});
 await dispatch({type:"thread.model-selection.set",threadId,modelSelection:{instanceId:"devReplay",model:"multi-turn"}});
 const target=Number(targetStr),begin=performance.now();
 for(let i=1;i<=target+11;i++){
 if(i===target+1){log({stage:"ready",seedTurns:target});while(!existsSync(out+"/measure.go"))await nap(100);}
 const before=latest(threadId).ordinal;
 const start=performance.now();
 await send("Respond with the next recorded fixture turn");
 const result=await wait(threadId,r=>r.ordinal>before&&r.status==="completed");
 if(i%100===0||i>target)log({stage:i>target?"measurement":"seed",turn:i,totalMs:performance.now()-start,elapsedSeconds:(performance.now()-begin)/1000,ordinal:result.ordinal});
 }
 const final=await req("orchestration.getThreadProjection",{threadId});
 log({stage:"final",runs:final.runs.length,attempts:final.attempts.length,completedTurns:final.providerTurns.filter(t=>t.status==="completed").length,providerThreads:final.providerThreads.length,stoppedCohort:final.runs[0].delegatedCompletion,task:final.subagents[0],lastMessages:final.messages.slice(-4).map(m=>({role:m.role,text:m.text}))});
 });
})).pipe(Effect.provide(NodeServices.layer)));
db.close();
