import base64, json, os, urllib.request, urllib.parse

org = os.environ['AZURE_DEVOPS_TEST_ORG'].rstrip('/')
project = urllib.parse.quote(os.environ['AZURE_DEVOPS_TEST_PROJECT'], safe='')
root = org + '/' + project + '/_apis/git/'
auth = 'Basic ' + base64.b64encode((':' + os.environ['AZURE_DEVOPS_EXT_PAT']).encode()).decode()
def api(path, body=None, method=None):
    request = urllib.request.Request(root + path + ('&' if '?' in path else '?') + 'api-version=7.1', data=None if body is None else json.dumps(body).encode(), headers={'Authorization': auth, 'Content-Type':'application/json'}, method=method)
    with urllib.request.urlopen(request) as response: return json.load(response)

repos = api('repositories')['value']
repo = repos[0]
prefix = 'repositories/' + repo['id'] + '/'
refs = api(prefix + 'refs?filter=heads/')
branches = {r['name']: r['objectId'] for r in refs['value']}
base = 'refs/heads/proof-25801-base'
head = 'refs/heads/proof-25801-unicode'
text = 'não permitido edição — İı Şş Ğğ → 😀'
zero = '0'*40
push = api(prefix + 'pushes', {'refUpdates':[{'name':base,'oldObjectId':zero}], 'commits':[{'comment':'Unicode proof fixture','changes':[{'changeType':'add','item':{'path':'/proof-25801.txt'},'newContent':{'content':'baseline','contentType':'rawtext'}}]}]})
sha = push['refUpdates'][0]['newObjectId']
api(prefix+'pushes', {'refUpdates':[{'name':head,'oldObjectId':zero}], 'commits':[{'comment':'Unicode proof change','parents':[sha],'changes':[{'changeType':'edit','item':{'path':'/proof-25801.txt'},'newContent':{'content':text,'contentType':'rawtext'}}]}]})
pr = api(prefix+'pullrequests', {'sourceRefName':head,'targetRefName':base,'title':text,'description':text})
number = pr['pullRequestId']
api(prefix+f'pullrequests/{number}/threads', {'comments':[{'parentCommentId':0,'content':text,'commentType':1}],'status':1})
print(json.dumps({'repositoryId':repo['id'],'repositoryUrl':repo['remoteUrl'],'pullRequestId':number,'baseBranch':base,'headBranch':head,'expected':text}, ensure_ascii=False))
