import os, subprocess, json, pathlib, time, argparse
p=argparse.ArgumentParser();p.add_argument('root');p.add_argument('--cleanup',action='store_true');a=p.parse_args()
root=pathlib.Path(a.root); manifest=root/'fixture.json'
org=os.environ['AZURE_DEVOPS_TEST_ORG'];project=os.environ['AZURE_DEVOPS_TEST_PROJECT']
def az(*args):
 scope=[] if args[:3]==('repos','pr','update') else ['--project',project]
 return json.loads(subprocess.check_output(['az',*args,'--organization',org,*scope,'-o','json'],text=True))
def git(*args):
 return subprocess.check_output(['git',*args],cwd=root/'repo',text=True).strip()
if a.cleanup:
 d=json.loads(manifest.read_text())
 for pr in d['prs']: az('repos','pr','update','--id',str(pr),'--status','abandoned')
 for branch in d['branches']:
  git('-c', 'credential.helper=!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f','push',d['remote'],'--delete',branch)
else:
 repo=az('repos','list')[0];remote=repo['remoteUrl'];prefix='proof29918-'+str(int(time.time()))
 (root/'repo').mkdir();git('init','-b',prefix+'-base');git('config','user.name','Proof fixture');git('config','user.email','proof@example.invalid')
 for f in ['a.ts','b.ts','c.ts','g.ts']: (root/'repo'/f).write_text('export const value = 1;\n')
 git('add','.');git('commit','-m','Synthetic base');base=git('rev-parse','HEAD'); branches=[prefix+'-base'];prs=[]
 def push(b):git('-c','credential.helper=!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f','push',remote,b)
 push(branches[0])
 manifest.write_text(json.dumps(dict(remote=remote,branches=branches,prs=prs,repo=repo['name'])))
 for i in range(10):
  branch=prefix+'-feature-'+str(i);git('checkout','-b',branch,base)
  for f in ['a.ts','b.ts','c.ts','g.ts']: (root/'repo'/f).write_text(f'export const value = {i+2};\nexport const changed = true;\n')
  git('add','.');git('commit','-m','Synthetic four-file change');push(branch);branches.append(branch)
  pr=az('repos','pr','create','--repository',repo['id'],'--source-branch',branch,'--target-branch',branches[0],'--title',f'Performance proof {i+1}','--description','Synthetic four-file change for PR opening measurement.');prs.append(pr['pullRequestId'])
  manifest.write_text(json.dumps(dict(remote=remote,branches=branches,prs=prs,repo=repo['name'],base=base)))
  print('Created fixture',i+1,flush=True)
