// Run from apps/server after copying this file there: node reproduce.ts <new-output-directory>
// Calls the production Git checkpoint service; all Git subprocesses are real.
import { execFileSync } from 'node:child_process';
import { mkdirSync, writeFileSync, existsSync } from 'node:fs';
import path from 'node:path';
import * as Effect from 'effect/Effect';
import * as Layer from 'effect/Layer';
import * as NodeServices from '@effect/platform-node/NodeServices';
import * as NodeCrypto from '@effect/platform-node/NodeCrypto';
import * as GitVcsDriver from './src/vcs/GitVcsDriver.ts';
import * as VcsProcess from './src/vcs/VcsProcess.ts';
import { CheckpointRef } from '@t3tools/contracts';
const output = path.resolve(process.argv[2]!);
mkdirSync(output, { recursive: true });
const git = (cwd: string, ...args: string[]) => execFileSync('git', args, {cwd, encoding:'utf8', stdio:['ignore','pipe','pipe']}).trim();
const init = (name: string) => {
 const cwd = path.join(output,name); mkdirSync(cwd);
 git(cwd,'init','-q'); git(cwd,'config','user.name','Checkpoint Demo'); git(cwd,'config','user.email','demo@example.invalid');
 writeFileSync(path.join(cwd,'file.txt'),'original\n'); git(cwd,'add','.'); git(cwd,'commit','-qm','initial'); return cwd;
};
const leaf=init('leaf-source'), library=init('library-source'), root=init('outer'), plain=init('plain');
const add = (cwd: string, source: string, name: string) => {
 git(cwd,'-c','protocol.file.allow=always','submodule','add','-q',source,name); git(cwd,'commit','-qam',`add ${name}`);
};
add(library,leaf,'nested'); add(root,library,'library');
git(root,'-c','protocol.file.allow=always','submodule','update','--init','--recursive');
const scopes=[root,path.join(root,'library'),path.join(root,'library/nested')];
const names=['outer','child','nested child'];
const ref=CheckpointRef.make('refs/t3/checkpoints/proof');
console.log('Checkpoint cleanup runtime demonstration');
console.log('Commit: '+git(process.cwd(),'rev-parse','HEAD'));
console.log('Environment: Linux; '+git(process.cwd(),'--version')+'; Node '+process.version);
console.log('Production GitVcsDriver + VcsProcess + Node subprocess services; no test runner or fake Git.');
const program=Effect.gen(function*(){
 const live=yield* VcsProcess.VcsProcess;
 let tracing=false;
 const driver=yield* GitVcsDriver.makeVcsDriverShape().pipe(Effect.provideService(VcsProcess.VcsProcess,{
  run: input => { if(tracing) console.log('git ['+(input.cwd===plain?'plain':names[scopes.indexOf(input.cwd)]??'other')+'] '+input.args.map(arg => arg.startsWith(output) ? '<fixture>/'+path.relative(output,arg) : arg).join(' ')); return live.run(input); }
 }));
 console.log('\n1. Capture checkpoint in initialized outer -> child -> nested child.');
 yield* driver.checkpoints.captureCheckpoint({cwd:root,checkpointRef:ref});
 const show=()=>scopes.forEach((cwd,i)=>console.log(names[i]+': '+(git(cwd,'for-each-ref','--format=%(refname)','refs/t3/checkpoints')||'(no checkpoint refs)')));
 show();
 console.log('\n2. Remove outer .gitmodules with git rm; keep indexed gitlink and initialized children.');
 git(root,'rm','--','.gitmodules');
 console.log('.gitmodules exists: '+existsSync(path.join(root,'.gitmodules')));
 console.log('Outer index:\n'+git(root,'ls-files','--stage'));
 console.log('\n3. Call production checkpoints.deleteCheckpointRefs on outer.');
 tracing=true;
 yield* driver.checkpoints.deleteCheckpointRefs({cwd:root,checkpointRefs:[ref]});
 tracing=false;
 console.log('\n4. Inspect real Git refs after cleanup.'); show();
 console.log('\n5. Same cleanup for a committed repository with no gitlinks.');
 yield* driver.checkpoints.captureCheckpoint({cwd:plain,checkpointRef:ref});
 tracing=true;
 yield* driver.checkpoints.deleteCheckpointRefs({cwd:plain,checkpointRefs:[ref]});
 tracing=false;
 console.log('plain: '+(git(plain,'for-each-ref','--format=%(refname)','refs/t3/checkpoints')||'(no checkpoint refs)'));
});
await Effect.runPromise(program.pipe(Effect.scoped,Effect.provide(VcsProcess.layer.pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer,NodeCrypto.layer))))));
