import { DatabaseSync } from 'node:sqlite';
import { writeFileSync, mkdirSync, existsSync } from 'node:fs';
import { makeState, runPromise } from './t3.ts';
const [home, out] = process.argv.slice(2);
mkdirSync(out, {recursive:true});
const state = makeState(home!, process.env);
const db = new DatabaseSync(home + '/userdata/statev2.sqlite',{readOnly:true});
const items = (id: string) => db.prepare('select payload_json from orchestration_v2_projection_turn_items where thread_id=? order by ordinal').all(id).map((r:any)=>JSON.parse(r.payload_json));
const log = (label: string, value: unknown) => {
 const entry = {at:new Date().toISOString(),label,value};
 console.log(JSON.stringify(entry));
};
const cli = async (args: string[]) => JSON.parse((await runPromise(state.cli(['thread', ...args, '--json']))).stdout);
const project = await state.state.project('Queue demonstration');
const prompt = 'This is a controlled steering demonstration. Run 18 separate shell tool calls, each running sleep 5 followed by echo STEP_N, one call at a time. Do not combine calls. Stay active until all 18 finish. If a message says Correction for the current turn, acknowledge CURRENT_CORRECTION_RECEIVED immediately in commentary and continue the sleep calls. If a message says Handle this later, acknowledge LATER_MESSAGE_RECEIVED. Do not inspect files or do other work.';
const receiver = await cli(['start', project, prompt, '--title', 'Receiver B', '--provider', 'codex', '--model', 'gpt-6.1-sol']);
log('receiver-start',receiver);
writeFileSync(out + '/ids.json',JSON.stringify({receiver}));
const show = () => cli(['show', receiver.threadId]);
for(let n=0;n<60;n++) {
 const snapshot = await show();
 writeFileSync(out+'/receiver-latest.json',JSON.stringify(snapshot,null,2));
 const text = JSON.stringify(items(receiver.threadId));
 if(text.includes('STEP_1') && text.includes('tool')) break;
 if(n===59) throw new Error('Receiver did not start tools');
 await new Promise(r=>setTimeout(r,1000));
}
log('receiver-tools-started', 'Real Codex active across sequential shell calls');
if(process.env.PROOF_GATE) { log('ready-for-recording',receiver); while(!existsSync(out+'/go')) await new Promise(r=>setTimeout(r,250)); }
const senderPrompt = `Use the T3 MCP tools to send exactly two messages to receiver thread ${receiver.threadId}. First call t3_thread_send with mode queue and exact message "Handle this later". Then immediately call t3_thread_send with mode auto and exact message "Correction for the current turn". Do not wait for the receiver or make other tool calls between the sends. Report the delivery field of both receipts. Then finish.`;
const actualPrompt = process.env.PROOF_CONTROL ? `Use t3_thread_send targeting ${receiver.threadId} with mode auto and exact message "Correction for the current turn". Report its delivery receipt and finish.` : senderPrompt;
const sender = await cli(['start', project, actualPrompt,'--title','Sender A','--provider','codex','--model','gpt-6.1-sol']);
log('sender-start',sender);
writeFileSync(out+'/ids.json',JSON.stringify({receiver,sender}));
for(let n=0;n<120;n++) {
 const a = await cli(['show',sender.threadId]);
 const b = await show();
 writeFileSync(out+'/sender-latest.json',JSON.stringify(a,null,2));
 writeFileSync(out+'/receiver-latest.json',JSON.stringify(b,null,2));
 if(n%3===0) log('runtime', {sender:a,receiver:b,senderItems:items(sender.threadId),receiverItems:items(receiver.threadId)});
 const text=JSON.stringify(a);
 if(text.includes('Correction for the current turn') && (text.includes('steered')||text.includes('queued')) && n>15) {log('final',{sender:a,receiver:b,senderItems:items(sender.threadId),receiverItems:items(receiver.threadId)});break;}
 await new Promise(r=>setTimeout(r,1000));
}
