import { mkdir, readFile, writeFile, watch } from 'node:fs/promises';
import { execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import * as Effect from 'effect/Effect';
import { rpcClient, runPromise } from './t3.ts';

const root = process.env.PROOF_ROOT!;
const side = process.env.PROOF_SIDE!;
const home = `${root}/${side}`;
const capture = `${root}/${side}-requests.ndjson`;
const workspace = `${home}/workspace-${randomUUID()}`;
await mkdir(workspace, {recursive:true});
await writeFile(`${workspace}/README.md`, 'Synthetic attachment budget reproduction.\n');
execFileSync('git',['init','--quiet','--initial-branch=main'],{cwd:workspace});
execFileSync('git',['add','.'],{cwd:workspace});
execFileSync('git',['-c','user.name=Proof','-c','user.email=proof@example.invalid','commit','--quiet','-m','Synthetic fixture'],{cwd:workspace});
await writeFile(capture,'');
const records: unknown[]=[];
async function nextRequest(previous: number) {
 const controller = new AbortController();
 const timer=setTimeout(()=>controller.abort(),120000);
 const watcher=watch(root,{signal:controller.signal});
 const check=async()=>{const lines=(await readFile(capture,'utf8')).trim().split('\n').filter(Boolean);return lines.length>previous?JSON.parse(lines.at(-1)!):undefined;};
 try { const existing=await check();if(existing)return existing;for await(const event of watcher){if(event.filename!==`${side}-requests.ndjson`)continue;const next=await check();if(next)return next;} } finally { clearTimeout(timer);controller.abort(); }
 throw new Error('No actual Codex turn/start request captured');
}
const results = await runPromise(Effect.gen(function*(){
 const client=yield* rpcClient(home,'http://127.0.0.1:17777');
 const projectId=randomUUID();
 yield* client['projects.mutate']({type:'project.create',commandId:randomUUID(),projectId,title:'Prompt budget proof',workspaceRoot:workspace});
 const source={kind:'snap-shot',capturedAt:'2026-08-24T11:00:00.000Z',appName:'Editor',windowTitle:'Demo',accessibleText:'Save button'};
 const png='iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=';
 let overhead=0;
 const summaries=[];
 for(const label of ['calibration','exact-limit','shorter-control']) {
  const threadId=randomUUID(),messageId=randomUUID();
  yield* client['orchestration.dispatchCommand']({type:'thread.create',commandId:randomUUID(),threadId,projectId,title:label,titleRenamed:true,createdBy:'user',creationSource:'web',modelSelection:{instanceId:'codex',model:'gpt-6-luna'},runtimeMode:'approval-required',interactionMode:'default',branch:null,worktreePath:null});
  const {attachments}=yield* client['assets.persistChatAttachments']({threadId,messageId,attachments:[{type:'image',name:'capture.png',mimeType:'image/png',sizeBytes:Buffer.from(png,'base64').length,dataUrl:`data:image/png;base64,${png}`,source}]});
  const chars=label==='calibration'?1:120000-overhead-(label==='shorter-control'?120:0);
  const next=nextRequest(records.length);
  yield* client['orchestration.dispatchCommand']({type:'message.dispatch',commandId:randomUUID(),threadId,messageId,text:'x'.repeat(chars),attachments:attachments.map(a=>({...a,source})),createdBy:'user',creationSource:'web',dispatchMode:{type:'start_immediately'}});
  const request=yield* Effect.promise(()=>next);
  records.push(request);
  const text=request.params.input.filter((part:any)=>part.type==='text').map((part:any)=>part.text).join('\n\n');
  if(label==='calibration')overhead=text.length-1;
  const tail=text.replace(/^x+/,`[${chars} x characters]`).replaceAll(root,'<proof-root>');
  const summary={label,userChars:chars,overhead,completePromptChars:chars+overhead,outboundChars:text.length,hasCapturedWindow:text.includes('Untrusted captured-window data follows'),hasSave:text.includes('Save button'),hasTruncationNotice:text.includes('context was truncated'),outboundText:tail};
  summaries.push(summary);
  console.log(JSON.stringify(summary,null,2));
  yield* client['orchestration.dispatchCommand']({type:'thread.stop',commandId:randomUUID(),threadId});
 }
 return summaries;
}).pipe(Effect.scoped));
await writeFile(`${root}/${side}-transcript.json`,JSON.stringify({surface:'Real T3 server; actual Codex app-server stdin captured transparently before forwarding unchanged',model:'gpt-6-luna',attachment:'Synthetic PNG with captured-window source metadata: Editor / Demo / Save button',results},null,2));
