import os, subprocess, json, pathlib, urllib.request, base64
org=os.environ['AZURE_DEVOPS_TEST_ORG'].rstrip('/')
project=os.environ['AZURE_DEVOPS_TEST_PROJECT']
def az(*args):
    return json.loads(subprocess.check_output(['az',*args,'--organization',org,'--project',project,'-o','json'],text=True))
repo=az('repos','list')[0]
root=pathlib.Path(__file__).parent/'azure-seed'
root.mkdir(exist_ok=True)
def git(*args):
    return subprocess.check_output(['git',*args],cwd=root,text=True).strip()
git('init','-q','-b','main')
git('config','user.name','Scenario')
git('config','user.email','scenario@example.invalid')
(root/'README.md').write_text('# Azure label reproduction\n')
git('add','.')
git('commit','-qm','Initial commit')
remote=repo['remoteUrl'].replace('t3code-factory-test@','')
helper='!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f'
git('-c','credential.helper='+helper,'push',remote,'main')
branch='factory-evidence-38008-labels'
git('checkout','-qb',branch)
(root/'release.txt').write_text('Release 1.0\n')
git('add','.')
git('commit','-qm','Prepare release 1.0')
git('-c','credential.helper='+helper,'push',remote,branch)
pr=az('repos','pr','create','--repository',repo['id'],'--source-branch',branch,'--target-branch','main','--title','Azure label reproduction 38008','--description','Synthetic pull request for label display evidence.')
endpoint=f"{org}/{project}/_apis/git/repositories/{repo['id']}/pullRequests/{pr['pullRequestId']}/labels?api-version=7.1"
req=urllib.request.Request(endpoint,data=json.dumps({'name':'release-1.0'}).encode(),method='POST',headers={'Content-Type':'application/json','Authorization':'Basic '+base64.b64encode((':'+os.environ['AZURE_DEVOPS_EXT_PAT']).encode()).decode()})
with urllib.request.urlopen(req) as r: print(r.read().decode())
state={'repositoryId':repo['id'],'remote':remote,'number':pr['pullRequestId'],'branch':branch,'mainCreated':True}
(pathlib.Path(__file__).parent/'azure-state.json').write_text(json.dumps(state))
print(json.dumps(state))
