import * as fs from 'node:fs';
import * as path from 'node:path';
import {spawn,spawnSync} from 'node:child_process';
import * as Effect from 'effect/Effect';
import * as Layer from 'effect/Layer';
import * as NodeServices from '@effect/platform-node/NodeServices';
import * as NodeWS from '@effect/platform-node/NodeWS';
import {RpcClient,RpcSerialization} from 'effect/rpc';
import {Socket} from 'effect/socket';
import {WsRpcGroup,ORCHESTRATION_PROTOCOL_VERSION} from '@t3tools/contracts';
const [side, mode='same']=process.argv.slice(2);
const home=`C:/proof/${side}-state`;
const origin=`http://127.0.0.1:${side==='base'?4310:4311}`;
const root=`C:/proof/${side}-${mode}/shop`;
const cli=(args)=>{const r=spawnSync(process.execPath,['src/bin.ts',...args,'--base-dir',home],{encoding:'utf8',timeout:120000});if(r.status!==0)throw Error(r.stderr+r.stdout);return r.stdout.trim();};
const clean=(s)=>String(s).replaceAll(/C:[\\/]+Users[\\/]+[^\\/]+/g,'<user>').replaceAll(/C:[\\/]+proof(?:-head|-base)?/g,'<evidence>').replaceAll(/V:[\\/]+/g,'<second-volume>/');
const log=(...args)=>console.log(...args.map(x=>clean(typeof x==='string'?x:JSON.stringify(x,null,2))));
const checkpoint=async(label)=>{
 await new Promise(resolve=>process.stdout.write('',resolve));
 return new Promise((resolve)=>{
 const folder=`C:/proof/${side}-${mode}-capture`;
 const ack=path.join(folder,`ack-${label}.txt`);
 const watcher=fs.watch(folder,()=>{if(fs.existsSync(ack)){watcher.close();resolve();}});
 fs.writeFileSync(path.join(folder,'checkpoint.txt'),label);
});};
const git=(cwd,...args)=>{const r=spawnSync('git',args,{cwd,encoding:'utf8'});if(r.status)throw Error(r.stderr);return r.stdout.trim();};
fs.writeFileSync(`C:/proof/${side}-${mode}-driver.pid`,String(process.pid));
fs.mkdirSync(root,{recursive:true});
for(const name of ['services/api','web','unpicked']){const p=path.join(root,name);fs.mkdirSync(p,{recursive:true});git(p,'init','-b','main');git(p,'config','user.name','Evidence');git(p,'config','user.email','evidence@example.invalid');fs.writeFileSync(path.join(p,'README.md'),name+'\n');git(p,'add','.');git(p,'commit','-m','Initial');}
for(const name of ['notes','.claude','.git-not','unborn'])fs.mkdirSync(path.join(root,name),{recursive:true});
fs.writeFileSync(path.join(root,'services','README.md'),'Shared services instructions\n');
fs.writeFileSync(path.join(root,'AGENTS.md'),'Shared project instructions\n');
fs.writeFileSync(path.join(root,'.claude','settings.json'),'{}\n');
fs.writeFileSync(path.join(root,'notes','shared.txt'),'Shared notes\n');
const tokenInfo=fs.readFileSync(`C:/proof/${side}-token.txt`,'utf8');
log('SERVER TOKEN',tokenInfo.split('\n').filter(l=>l.includes('Administrators') || l.includes('SeCreateSymbolicLinkPrivilege')).join('\n'),'SeCreateSymbolicLinkPrivilege present:',tokenInfo.includes('SeCreateSymbolicLinkPrivilege'));
log(`Windows Server 2025; real T3 server; basic-user token; ${side}; ${mode}-volume`);
const registration=cli(['project','add',root]);log('Project registration:',registration);
const projectId=registration.match(/project ([^ ]+)/)[1];
const token=cli(['auth','session','issue','--token-only','--label','evidence']);
const resp=await fetch(origin+'/api/auth/websocket-ticket',{method:'POST',headers:{authorization:'Bearer '+token}});const {ticket}=await resp.json();
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 rpc=yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
 const call=(method,input)=>rpc[method](input);
 yield* call('server.updateSettings',{patch:{worktreesDirectory:mode.startsWith('cross')?'V:/worktrees':`C:/proof/${side}-worktrees`}});
 log('Start New worktree thread: feature, base main, Replay (dev), shared folders and loose AGENTS.md');
 const started=yield* Effect.promise(()=>new Promise((resolve,reject)=>{const child=spawn(process.execPath,['src/bin.ts','thread','start',root,'Show the project status','--worktree','main','--branch','feature','--provider','devReplay','--model','todo-list','--wait','--json','--base-dir',home],{timeout:180000});let stdout='',stderr='';child.stdout.on('data',b=>stdout+=b);child.stderr.on('data',b=>stderr+=b);child.on('error',reject);child.on('close',status=>resolve({status,stdout,stderr}));}));
 log('THREAD START exit',started.status,'stdout',started.stdout,'stderr',started.stderr);
 const launched=JSON.parse(started.stdout);
 const id=launched.threadId;
 const shown=JSON.parse(cli(['thread','show',id,'--json']));
 log('THREAD STATE',{status:shown.thread.status,worktreePath:shown.thread.worktreePath,error:shown.error,messages:shown.messages});
 fs.writeFileSync(`C:/proof/${side}-${mode}-thread.json`,JSON.stringify({threadId:id,home,origin,root}));
 const target=shown.thread.worktreePath;
 if(!target || shown.error){log('SETUP FAILED',shown.error);yield* Effect.promise(()=>checkpoint('setup-failed'));return;}
 log('SETUP FINISHED',target);
 for(const name of ['AGENTS.md','services/README.md','.claude','notes','.git-not','services/api','web']){const p=path.join(target,name);const s=fs.lstatSync(p);log('DISK',name,{isLink:s.isSymbolicLink(),isFile:s.isFile(),sourceVolume:fs.statSync(path.join(root,name)).dev,targetVolume:s.dev,sourceInode:fs.statSync(path.join(root,name)).ino,targetInode:s.ino,content:s.isFile()?fs.readFileSync(p,'utf8'):fs.readdirSync(p)});}
 log('SHARED ENTRY SUMMARY',{runStatus:launched.status,replayReply:launched.reply,AGENTS:fs.readFileSync(path.join(target,'AGENTS.md'),'utf8'),sourceVolume:fs.statSync(path.join(root,'AGENTS.md')).dev,targetVolume:fs.statSync(path.join(target,'AGENTS.md')).dev,sameFileIdentity:fs.statSync(path.join(root,'AGENTS.md')).dev===fs.statSync(path.join(target,'AGENTS.md')).dev && fs.statSync(path.join(root,'AGENTS.md')).ino===fs.statSync(path.join(target,'AGENTS.md')).ino,claudeJunction:fs.lstatSync(path.join(target,'.claude')).isSymbolicLink(),notesContent:fs.readFileSync(path.join(target,'notes','shared.txt'),'utf8'),apiBranch:git(path.join(target,'services/api'),'branch','--show-current'),webBranch:git(path.join(target,'web'),'branch','--show-current')});
 yield* Effect.promise(()=>checkpoint('setup-finished'));
 const unborn=path.join(root,'unborn');git(unborn,'init','-b','main');
 log('Add repository with no commit; expected Git failure, followed by restoration of original shared path');
 const added=yield* call('workspace.addTaskFolderRepository',{threadId:id,repositoryPath:unborn,startFromOrigin:false}).pipe(Effect.result);log('ADD RESULT',added);
 log('RELINK', {isJunction:fs.lstatSync(path.join(target,'unborn')).isSymbolicLink(),target:fs.readlinkSync(path.join(target,'unborn')),originalStillExists:fs.existsSync(unborn)});
 yield* Effect.promise(()=>checkpoint('failed-add-relinked'));
 if(mode.startsWith('cross')){try{fs.linkSync(path.join(root,'AGENTS.md'),path.join(target,'hardlink-probe'));log('UNEXPECTED hardlink success');}catch(e){log('CROSS-VOLUME HARDLINK PROBE',e.code);}log('COPY FALLBACK', {sourceVolume:fs.statSync(path.join(root,'AGENTS.md')).dev,targetVolume:fs.statSync(path.join(target,'AGENTS.md')).dev,targetLinkCount:fs.statSync(path.join(target,'AGENTS.md')).nlink,bytesMatch:fs.readFileSync(path.join(root,'AGENTS.md')).equals(fs.readFileSync(path.join(target,'AGENTS.md')))});yield* Effect.promise(()=>checkpoint('copy-fallback'));}
 if(mode.endsWith('safety')){if(!mode.includes('copy-only'))fs.writeFileSync(path.join(target,'draft.txt'),'Only in the task folder\n');if(mode.startsWith('cross'))fs.writeFileSync(path.join(target,'AGENTS.md'),'Changed task copy\n');log(mode.includes('copy-only')?'SAFETY: changed only the copied AGENTS.md; no task-only draft exists':'SAFETY: created draft.txt only in task folder and changed copied AGENTS.md when cross-volume');}
 log('Close thread agent session before deleting its worktree');
 log('SESSION RELEASE',yield* call('orchestration.forceStopThread',{threadId:id}));
 log('DELETE THREAD',yield* call('orchestration.dispatchCommand',{type:'thread.delete',commandId:crypto.randomUUID(),threadId:id}));
 log('Remove thread worktree without force');
 const removed=yield* call('vcs.removeWorktree',{cwd:root,path:target,force:false}).pipe(Effect.result);log('REMOVE RESULT',removed);
 if(mode.endsWith('safety'))log('KEPT FILES',{draft:fs.existsSync(path.join(target,'draft.txt'))?fs.readFileSync(path.join(target,'draft.txt'),'utf8'):null,agents:fs.readFileSync(path.join(target,'AGENTS.md'),'utf8')});
 log('AFTER REMOVAL',{taskFolderExists:fs.existsSync(target),sourceAgents:fs.readFileSync(path.join(root,'AGENTS.md'),'utf8'),sourceNotes:fs.readFileSync(path.join(root,'notes','shared.txt'),'utf8'),sourceClaude:fs.readFileSync(path.join(root,'.claude','settings.json'),'utf8'),apiWorktrees:git(path.join(root,'services/api'),'worktree','list','--porcelain')});
 yield* Effect.promise(()=>checkpoint('cleanup'));
})).pipe(Effect.provide(NodeServices.layer)));

