import os,json,urllib.request,urllib.parse,base64,sys
org=os.environ['AZURE_DEVOPS_TEST_ORG'].rstrip('/')
project=urllib.parse.quote(os.environ['AZURE_DEVOPS_TEST_PROJECT'])
root=org+'/'+project+'/_apis/'
def api(path,data=None,method=None):
 req=urllib.request.Request(root+path+(' & ' if False else ('&' if '?' in path else '?'))+'api-version=7.1', data=None if data is None else json.dumps(data).encode(),method=method,headers={'Authorization':'Basic '+base64.b64encode((':'+os.environ['AZURE_DEVOPS_EXT_PAT']).encode()).decode(),'Content-Type':'application/json'})
 with urllib.request.urlopen(req) as r:
  body=r.read()
  return json.loads(body) if body else None
statepath=os.path.join(os.path.dirname(__file__),'azure-state.json')
if sys.argv[1]=='create':
 repo=api('git/repositories',{'name':'pr-42049-evidence-1'})
 json.dump(repo,open(statepath,'w'))
 print(repo['remoteUrl'])
elif sys.argv[1]=='policy':
 repo=json.load(open(statepath))
 policy=api('policy/configurations',{'isEnabled':True,'isBlocking':True,'type':{'id':'cbdc66da-9728-4af8-aada-9a5a32e4a226'},'settings':{'invalidateOnSourceUpdate':True,'statusName':'ci','statusGenre':'factory','scope':[{'repositoryId':repo['id'],'refName':'refs/heads/main','matchKind':'Exact'}]}})
 pr=api('git/repositories/'+repo['id']+'/pullrequests',{'sourceRefName':'refs/heads/feature','targetRefName':'refs/heads/main','title':'CI registration evidence'})
 repo['pr']=pr['pullRequestId'];repo['policy']=policy['id'];json.dump(repo,open(statepath,'w'));print(repo['pr'])
elif sys.argv[1] in ['pending','succeeded']:
 repo=json.load(open(statepath)); print(api('git/repositories/'+repo['id']+'/pullrequests/'+str(repo['pr'])+'/iterations/1/statuses',{'state':sys.argv[1],'description':'Scenario CI','context':{'name':'ci','genre':'factory'}})['state'])
elif sys.argv[1]=='cleanup':
 repo=json.load(open(statepath));api('git/repositories/'+repo['id']+'/pullrequests/'+str(repo['pr']),{'status':'abandoned'},'PATCH')
 api('policy/configurations/'+str(repo['policy']),method='DELETE')
