import * as http from 'node:http';
import {watch} from 'node:fs';
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import { ProviderDriverKind, ProviderInstanceId, ThreadId } from '@t3tools/contracts';
import { expect } from 'e2e';
import * as Effect from 'effect/Effect';
import { T3_HOME } from '../e2e.config.ts';
import { makeState, rpcClient, runPromise, test, WEB } from './t3.ts';

test('A stopped run cannot submit its delayed typed result to its successor', WEB, async ({t3,app,screen,browser}) => {
  const pending: Array<{release:()=>Promise<string>, arrived:Promise<void>}> = [];
  const waiters: Array<()=>void> = [];
  const transcript: string[] = [];
  const proxy = http.createServer(async (req,res) => {
    const parts: Buffer[]=[]; for await (const chunk of req) parts.push(Buffer.from(chunk));
    const body=Buffer.concat(parts);
    const target=new URL(req.url!, 'http://localhost').searchParams.get('target')!;
    if(body.length){try{const msg=JSON.parse(body.toString());console.log('Proxy MCP method:',msg.method,msg.params?.name??'');}catch{}}
    const forward=async()=>{
      const headers={...req.headers}; delete headers.host; delete headers.connection; delete headers['content-length'];
      const result=await fetch(target,{method:req.method,headers:headers as Record<string,string>, ...(body.length?{body}:{}),duplex:'half'} as RequestInit);
      const text=await result.text();
      if(!res.destroyed){res.writeHead(result.status,{'content-type':result.headers.get('content-type')??'application/json'});res.end(text);}
      return text;
    };
    if(body.toString().includes('t3_submit_output') && body.toString().includes('tools/call')){
      transcript.push(`Held typed-result request ${pending.length+1}`);
      pending.push({release:forward,arrived:Promise.resolve()}); waiters.splice(0).forEach(f=>f());
    }else {try{await forward();}catch(e){res.writeHead(502);res.end(String(e));}}
  });
  await new Promise<void>(resolve=>proxy.listen(0,'127.0.0.1',resolve));
  const port=(proxy.address() as {port:number}).port;
  const waitHeld=async(n:number)=>{while(pending.length<n) await Promise.race([new Promise<void>(r=>waiters.push(r)),new Promise<never>((_,reject)=>setTimeout(()=>reject(new Error('Typed-result POST did not reach loopback proxy')),120000))]);};
  const wrapper=`#!/usr/bin/env node
import {spawn} from 'node:child_process';
import {createInterface} from 'node:readline';
const rewrite=v=>typeof v==='string'?v.replace(/http:\\/\\/[^"\\s]+\\/mcp/g,u=>'http://127.0.0.1:${port}/?target='+encodeURIComponent(u)):Array.isArray(v)?v.map(rewrite):v&&typeof v==='object'?Object.fromEntries(Object.entries(v).map(([k,x])=>[k,rewrite(x)])):v;
const args=process.argv.slice(2).map(a=>{try{return JSON.stringify(rewrite(JSON.parse(a)))}catch{return rewrite(a)}});
const p=spawn('/usr/local/bin/claude',args,{stdio:['pipe','inherit','inherit']});p.on('exit',c=>process.exit(c??1));
createInterface({input:process.stdin}).on('line',line=>{try{p.stdin.write(JSON.stringify(rewrite(JSON.parse(line)))+'\\n')}catch{p.stdin.write(line+'\\n')}});
process.stdin.on('end',()=>p.stdin.end());
for(const s of ['SIGTERM','SIGINT'])process.on(s,()=>p.kill(s));
`;
  try {
    const project=await t3.project('typed-result-demo',{'claude-proxy.mjs':wrapper,'result-schema.json':JSON.stringify({type:'object',properties:{value:{type:'string'}},required:['value'],additionalProperties:false})});
    await fs.chmod(path.join(project,'claude-proxy.mjs'),0o755);
    const instanceId=ProviderInstanceId.make('claude-proof');
    await runPromise(Effect.gen(function*(){const client=yield* rpcClient(T3_HOME,app.baseUrl??'');yield* client['server.updateSettings']({patch:{},providerInstanceMutation:{operation:'upsert',instanceId,instance:{driver:ProviderDriverKind.make('claudeAgent'),enabled:true,displayName:'Claude proof',config:{binaryPath:path.join(project,'claude-proxy.mjs')}}}});}).pipe(Effect.scoped));
    const {cli}=makeState(T3_HOME);
    const schema=path.join(project,'result-schema.json');
    await fs.writeFile(path.join(project,'proof-config.json'),JSON.stringify({database:path.join(T3_HOME,'userdata/statev2.sqlite')}));
    await fs.writeFile(path.join(project,'inspect-result.py'),`import sqlite3,json,pathlib,sys
config=json.loads(pathlib.Path('proof-config.json').read_text())
print('LIVE SERVER RESULT INSPECTOR (read-only)',flush=True)
print('Type inspect to read the real server projection.',flush=True)
pathlib.Path('inspector-ready').write_text('ready')
count=0
for line in sys.stdin:
 if line.strip()!='inspect': continue
 count+=1
 con=sqlite3.connect('file:'+config['database']+'?mode=ro',uri=True)
 rows=con.execute('select payload_json from orchestration_v2_projection_runs order by ordinal').fetchall()
 con.close()
 print('\\n'+('AFTER RELEASING STOPPED RUN A' if count==1 else 'AFTER RELEASING RUN B'),flush=True)
 reply=json.loads(pathlib.Path('last-mcp-response.json').read_text())['result']
 print('MCP isError: '+str(reply.get('isError')),flush=True)
 for item in reply.get('content',[]):
  if 'no longer active' in item.get('text',''): print(json.loads(item['text'])['message'],flush=True)
 for row in rows:
  run=json.loads(row[0]);output=run.get('output',{}).get('value')
  print('Run '+str(run['ordinal'])+' | '+run['status']+' | stored output: '+json.dumps(output),flush=True)
 pathlib.Path('inspection-done').write_text(str(count))
`);
    const inspect=async()=>{
      const done=new Promise<void>(resolve=>{const watcher=watch(project,async(_event,name)=>{if(name==='inspection-done'){watcher.close();resolve();}});});
      await screen.getByLabel('Terminal input').focus();
      await browser.keyboard.type('inspect\n');
      await done;
    };
    const started=await runPromise(cli(['thread','start',project,'Run A: Call t3_submit_output with json {"value":"A"} immediately. Do not use other tools.','--title','Delayed typed result','--provider',instanceId,'--model','claude-haiku-5-5','--output-schema',schema,'--json']));
    const {threadId}=JSON.parse(started.stdout);
    await t3.open({threadId});
    await waitHeld(1).catch(async error=>{await app.screenshot('provider-request-not-arrived');throw error;});
    await app.screenshot('run-a-held');
    await screen.getByRole('button','Stop generation').tap();
    await screen.getByRole('button','Stop generation').waitFor({state:'hidden'});
    await runPromise(cli(['thread','send',threadId,'Run B: Call t3_submit_output with json {"value":"B"} immediately. Do not use other tools.','--output-schema',schema,'--json']));
    await waitHeld(2);
    transcript.push('Run A stopped; Run B active with its own result still held.');
    const ready=new Promise<void>(resolve=>{const watcher=watch(project,(_event,name)=>{if(name==='inspector-ready'){watcher.close();resolve();}});});
    await screen.getByRole('button','Toggle terminal drawer').tap();
    await ready;
    await screen.getByLabel('Terminal input').waitFor();
    const late=await pending[0].release(); transcript.push('Released A: '+late);
    await fs.writeFile(path.join(project,'last-mcp-response.json'),late);
    await inspect();
    await app.screenshot('late-result-released');
    const projection=await runPromise(Effect.gen(function*(){const client=yield* rpcClient(T3_HOME,app.baseUrl??'');return yield* client['orchestration.getThreadProjection']({threadId:ThreadId.make(threadId)});}).pipe(Effect.scoped));
    const successor=projection.runs.find(r=>r.ordinal===2);
    transcript.push('Run B output after late A: '+JSON.stringify(successor?.output??null));
    const own=await pending[1].release(); transcript.push('Released B: '+own);
    await fs.writeFile(path.join(project,'last-mcp-response.json'),own);
    await inspect();
    const finished=await runPromise(Effect.gen(function*(){const client=yield* rpcClient(T3_HOME,app.baseUrl??'');return yield* client['orchestration.getThreadProjection']({threadId:ThreadId.make(threadId)});}).pipe(Effect.scoped));
    const ownOutput=finished.runs.find(r=>r.ordinal===2)?.output;
    transcript.push('Run B output after its own submission: '+JSON.stringify(ownOutput??null));
    await app.screenshot('own-result-released');
    console.log(transcript.join('\n'));
    await fs.writeFile(path.join(T3_HOME,'typed-result-transcript.txt'),transcript.join('\n'));
    await fs.writeFile(path.join(process.env.T3_PROOF_SCRATCH!,'transcript-'+Date.now()+'.txt'),transcript.join('\n'));
    expect(late).toContain('"isError":true');
    expect(successor?.output).toBeUndefined();
    expect(ownOutput?.value).toEqual({value:'B'});
    expect(own).not.toContain('"isError":true');
  } finally {proxy.closeAllConnections();await new Promise<void>(resolve=>proxy.close(()=>resolve()));}
});
