import os, sys, subprocess, pathlib, hashlib, json, datetime, textwrap
from PIL import Image, ImageDraw, ImageFont
ROOT=pathlib.Path(__file__).parent
run=ROOT/('run-'+datetime.datetime.now().strftime('%Y%m%d-%H%M%S')); run.mkdir()
font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',18)
clean={k:v for k,v in os.environ.items() if not k.startswith('GIT_')}
node='''const {makeCheckpointWorkspace}=await import(process.argv[1]); const p=await makeCheckpointWorkspace('standalone-probe'); console.log('WORKSPACE='+p);'''
for side,checkout in [('before',sys.argv[1]),('after',sys.argv[2])]:
 out=run/side; out.mkdir(); lines=[]; frames=[]
 def say(s):
  lines.extend(part for line in s.splitlines() for part in (textwrap.wrap(line, width=128) or [''])); print(s,flush=True)
  im=Image.new('RGB',(1500,1050),'#10151d'); d=ImageDraw.Draw(im)
  for i,l in enumerate(lines): d.text((25,20+i*25),l,font=font,fill='#e0e7ee')
  p=out/('frame-%03d.png'%len(frames)); im.save(p); frames.append(p)
 def git(*args,cwd=None):
  return subprocess.check_output(['git',*args],cwd=cwd,env=clean,stderr=subprocess.DEVNULL,text=True).strip()
 outer=out/'outer'; linked=out/'linked'; outer.mkdir()
 git('init','-b','main',cwd=outer); git('config','user.name','Owner',cwd=outer);git('config','user.email','owner@example.com',cwd=outer)
 (outer/'base.txt').write_text('base\n'); git('add','.',cwd=outer);git('commit','-m','base',cwd=outer);git('worktree','add','-b','feature',str(linked),cwd=outer)
 selector=outer/'.git/worktrees/linked'; temp=out/'temp';temp.mkdir()
 def snapshot():
  return {str(p.relative_to(outer/'.git')):hashlib.sha256(p.read_bytes()).hexdigest() for p in (outer/'.git').rglob('*') if p.is_file()}
 sha=git('rev-parse','HEAD',cwd=checkout); start=snapshot(); old=git('rev-parse','feature',cwd=outer)
 say('Standalone replay-workspace reproduction | Linux / Node / Git\n'+side.upper()+' commit '+sha+'\nFresh scratch outer repository + linked worktree on feature\n$ git log -1 feature --format="%s | %an <%ae>"\n'+git('log','-1','feature','--format=%s | %an <%ae>',cwd=outer))
 say('$ GIT_DIR=<outer>/.git/worktrees/linked node <standalone driver>\nDriver calls the real makeCheckpointWorkspace("standalone-probe")')
 env=clean|{'GIT_DIR':str(selector),'TMPDIR':str(temp)}
 source=pathlib.Path(checkout)/'packages/provider-testing/src/replayWorkspace.ts'
 p=subprocess.run(['node','--input-type=module','-e',node,str(source)],cwd=checkout,env=env,text=True,capture_output=True)
 workspace=next((l[10:] for l in p.stdout.splitlines() if l.startswith('WORKSPACE=')),None)
 say('Command exit: '+str(p.returncode)+' | temp workspace returned: '+str(bool(workspace)))
 end=snapshot(); changed=sorted(k for k in start.keys()|end.keys() if start.get(k)!=end.get(k))
 say('$ git config --local --get core.bare\n'+git('config','--local','--get','core.bare',cwd=outer)+'\n$ git config --local --get user.name\n'+git('config','--local','--get','user.name',cwd=outer)+'\n$ git log -1 feature --format="%s | %an <%ae>"\n'+git('log','-1','feature','--format=%s | %an <%ae>',cwd=outer))
 say('Calling repository feature ref unchanged: '+str(old==git('rev-parse','feature',cwd=outer))+'\nCalling repository .git files byte-for-byte unchanged: '+str(not changed)+'\nChanged files: '+(', '.join(k for k in changed if not k.startswith(('objects/','logs/')) and not k.endswith('logs/HEAD')) if changed else '(none)'))
 if workspace:
  q=subprocess.run(['git','-C',workspace,'rev-parse','--is-inside-work-tree'],env=clean,text=True,capture_output=True)
  say('Returned workspace is its own Git working tree: '+str(q.returncode==0 and q.stdout.strip()=='true'))
 say('OBSERVED: '+('Calling repository was modified by fixture Git.' if changed else 'Fixture Git stayed in its temporary repository.'))
 (out/'transcript.txt').write_text('\n'.join(lines)+'\n')
 (out/'raw.json').write_text(json.dumps({'sha':sha,'exitCode':p.returncode,'stdout':p.stdout.replace(str(out),'<scratch>'),'stderr':p.stderr.replace(str(out),'<scratch>'),'changedGitFiles':changed},indent=2))
 frames[-1].replace(out/'capture.png');frames[-1]=out/'capture.png'
 concat=out/'frames.txt';concat.write_text(''.join("file '%s'\nduration 2\n"%f for f in frames)+"file '%s'\n"%frames[-1])
 subprocess.run(['ffmpeg','-y','-v','error','-f','concat','-safe','0','-i',str(concat),'-vf','format=yuv420p','-c:v','libx264','-r','10',str(out/'recording.mp4')],check=True)
print('EVIDENCE='+str(run))
