import os,json,urllib.request,base64,pathlib
org=os.environ['AZURE_DEVOPS_TEST_ORG'].rstrip('/')
project=os.environ['AZURE_DEVOPS_TEST_PROJECT']
root=org+'/'+urllib.parse.quote(project) +'/_apis/git'
def api(path,data=None,method=None):
 req=urllib.request.Request(root+path+ ('&' if '?' in path else '?')+'api-version=7.1',data=json.dumps(data).encode() if data is not None else None,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
state=pathlib.Path(__file__).with_name('azure-state.json')
if os.environ.get('CLEANUP'):
 s=json.loads(state.read_text())
 for pr in api('/repositories/'+s['id']+'/pullrequests')['value']:
  api('/repositories/'+s['id']+'/pullrequests/'+str(pr['pullRequestId']),{'status':'abandoned'},method='PATCH')
 api('/repositories/'+s['id'],method='DELETE');print('abandoned PRs and deleted test repository');raise SystemExit
r=api('/repositories',{'name':'pr44798-cr-proof-20261128'})
state.write_text(json.dumps({'id':r['id']}))
p='/repositories/'+r['id']
push=api(p+'/pushes',{'refUpdates':[{'name':'refs/heads/main','oldObjectId':'0'*40}],'commits':[{'comment':'Initial sample','changes':[{'changeType':'add','item':{'path':'/README.md'},'newContent':{'content':'Recording segmentation proof','contentType':'rawtext'}}]}]})
sha=push['commits'][0]['commitId']
for branch,sep in [('demo','\r'),('demo-lf','\n')]:
 api(p+'/pushes',{'refUpdates':[{'name':'refs/heads/'+branch,'oldObjectId':'0'*40}],'commits':[{'comment':'Sample change','parents':[sha],'changes':[{'changeType':'add','item':{'path':'/'+branch+'.txt'},'newContent':{'content':'Sample change','contentType':'rawtext'}}]}]})
 body=sep.join(['```text','https://example.com/sample.mp4','```','','https://github.com/user-attachments/assets/12345678-1234-1234-1234-123456789abc.mp4','','- [ ] Done'])
 pr=api(p+'/pullrequests',{'sourceRefName':'refs/heads/'+branch,'targetRefName':'refs/heads/main','title':'Recording after code fence ('+('bare CR' if sep=='\r' else 'LF control')+')','description':body})
 assert api(p+'/pullrequests/'+str(pr['pullRequestId']))['description']==body
 print(branch,pr['pullRequestId'])
pathlib.Path(__file__).with_name('remote.txt').write_text(r['remoteUrl'])
print('created and verified descriptions')
