import os, sys, pathlib, json, subprocess, urllib.request, base64, time
# Usage: fixture.py setup|push CHECKOUT T3_HOME RUN_DIRECTORY
mode, checkout, home, run = sys.argv[1:]
run=pathlib.Path(run); run.mkdir(parents=True,exist_ok=True)
host=os.environ.get('ISSUE_FORGE_URL','http://127.0.0.1:33053')
auth='Basic '+base64.b64encode(('reviewer:'+os.environ['ISSUE_FORGE_PASSWORD']).encode()).decode()
def git(cwd,*args):
 return subprocess.check_output(['git',*args],cwd=cwd,stderr=subprocess.PIPE,text=True).strip()
def push(cwd,branch):
 git(cwd,'-c','http.extraHeader=Authorization: '+auth,'push','-u','origin',branch)
def commit(cwd,msg):
 git(cwd,'add','.'); git(cwd,'-c','user.name=Reviewer','-c','user.email=reviewer@example.invalid','commit','-m',msg)
def api(path, body):
 req=urllib.request.Request(host+'/api/v1'+path,data=json.dumps(body).encode(),headers={'Authorization':auth,'Content-Type':'application/json'})
 return json.load(urllib.request.urlopen(req))
if mode=='setup':
 name='viewed-proof-'+str(time.time_ns())
 api('/user/repos',{'name':name,'default_branch':'main'})
 repo=run/'viewed-proof'; (repo/'src').mkdir(parents=True)
 for f,s in {'a.ts':'export const a = 1;\n','b.ts':'export const b = 1;\n','greeting.ts':'export const greeting = "hello";\n'}.items(): (repo/'src'/f).write_text(s)
 git(repo,'init','--initial-branch=main'); commit(repo,'Initial examples')
 remote=host+'/reviewer/'+name+'.git'
 git(repo,'remote','add','origin',remote); push(repo,'main'); git(repo,'checkout','-b','greeting')
 for f,s in {'a.ts':'export const a = 2;\n','b.ts':'export const b = 2;\n','greeting.ts':'export const greeting = "hello there";\n'}.items(): (repo/'src'/f).write_text(s)
 commit(repo,'Update greeting and examples'); push(repo,'greeting')
 for attempt in range(20):
  try:
   pr=api('/repos/reviewer/'+name+'/pulls',{'title':'Update greeting','head':'greeting','base':'main','body':'Synthetic review fixture'}); break
  except urllib.error.HTTPError as e:
   if e.code!=404: raise
   time.sleep(.5)
 clone=run/'push-clone'; git(run,'clone','--branch','greeting',remote,str(clone))
 subprocess.run(['vp','exec','node','apps/server/src/bin.ts','project','add',str(repo),'--title','Viewed proof','--base-dir',home],cwd=checkout,check=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
 data={'repository':name,'prUrl':pr['html_url'],'displayedBlob':git(repo,'rev-parse','HEAD:src/greeting.ts')}
 (run/'state.json').write_text(json.dumps(data,indent=2)); print(json.dumps(data))
else:
 clone=run/'push-clone'; (clone/'src/greeting.ts').write_text('export const greeting = "hello friend";\n')
 commit(clone,'Push a greeting the reviewer has not loaded'); push(clone,'greeting')
 data=json.loads((run/'state.json').read_text()); data['pushedBlob']=git(clone,'rev-parse','HEAD:src/greeting.ts')
 (run/'state.json').write_text(json.dumps(data,indent=2)); print(json.dumps(data))
