#!/usr/bin/python3
import json,os,sys
args=sys.argv[1:];root=os.environ['PROOF_ROOT'];state=json.load(open(root+'/state.json'));mode=state['mode'];name=None;code=0;stderr=''
if args[:3]==['repos','pr','show']:
 name='show-no-location' if state.get('noLocation') else 'show'
 if state.get('showDeny'):code=1;stderr='synthetic show denied'
elif args[:4]==['repos','pr','policy','list']:
 skip=int(args[args.index('--skip')+1]);name=state.get('pages',{}).get(str(skip),'empty')
 if mode=='denied':code=1;stderr='synthetic policy read denied'
 elif mode=='auth':code=1;stderr='Please run az login to setup account.'
 elif mode=='rate':code=1;stderr='429 Too Many Requests rate limit exceeded'
 elif mode=='notfound':code=1;stderr='TF401180: The requested pull request was not found.'
elif args[:2]==['devops','invoke']:
 resource=args[args.index('--resource')+1]
 if resource=='pullRequestIterations':
  name='iterations-empty' if state.get('iterationsEmpty') else 'iterations-'+state.get('head','a')
  if state.get('iterationsDeny'):code=1;stderr='synthetic iterations unavailable'
 elif resource=='pullRequestIterationChanges':name='changes'
else:code=99;stderr='UNEXPECTED COMMAND (no real az fallback)'
if name is None and not code:code=99;stderr='UNEXPECTED RESOURCE'
logpath=root+'/'+os.environ['PROOF_REVISION']+'-argv.jsonl'
sequence=sum(1 for _ in open(logpath)) + 1 if os.path.exists(logpath) else 1
with open(logpath,'a') as log:log.write(json.dumps(dict(sequence=sequence,argv=['az']+args,cwd=os.getcwd(),scenario=state['scenario'],event=state['event'],mode=mode,selectedFixture=name,exitCode=code,stderr=stderr))+'\n')
if code:print(stderr,file=sys.stderr);sys.exit(code)
sys.stdout.write(open(root+'/fixtures/'+name+'.json').read())
