import os, json, urllib.request, urllib.parse, base64, subprocess, pathlib
root=pathlib.Path(__file__).parent
org=os.environ['AZURE_DEVOPS_TEST_ORG'].rstrip('/')
project=urllib.parse.quote(os.environ['AZURE_DEVOPS_TEST_PROJECT'])
auth='Basic '+base64.b64encode((':'+os.environ['AZURE_DEVOPS_EXT_PAT']).encode()).decode()
def request(url,method='GET',data=None,ctype='application/json'):
    req=urllib.request.Request(url, data=data, method=method, headers={'Authorization':auth,'Content-Type':ctype})
    with urllib.request.urlopen(req) as r: return json.load(r)
repository=request(f'{org}/{project}/_apis/git/repositories?api-version=7.1','POST',json.dumps({'name':'attachment-proof-36148-e4'}).encode())
rid=repository['id']
api=f'{org}/{project}/_apis/git/repositories/{rid}'
subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-f','lavfi','-i','testsrc2=size=480x270:rate=15','-t','6','-vf',"drawtext=fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf:text='%{pts\\:hms}':x=8:y=8:fontsize=22:fontcolor=white:box=1:boxcolor=black@0.7",'-c:v','libx264','-pix_fmt','yuv420p','-y',str(root/'demo.mp4')],check=True)
subprocess.run(['ffmpeg','-hide_banner','-loglevel','error','-i',str(root/'demo.mp4'),'-t','2','-vf','fps=5,scale=320:180','-y',str(root/'demo.gif')],check=True)
repo=root/'synthetic-repo'; repo.mkdir(exist_ok=True)
def git(*args): subprocess.run(['git',*args],cwd=repo,check=True,stdout=subprocess.DEVNULL)
git('init','-b','main')
(repo/'README.md').write_text('Synthetic attachment demonstration\n')
git('add','.')
git('-c','user.name=Scenario','-c','user.email=scenario@example.invalid','commit','-m','Initial')
remote=f'{org}/{project}/_git/attachment-proof-36148-e4'
git('remote','add','origin',remote)
helper='!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f'
git('-c','credential.helper='+helper,'push','origin','main')
git('checkout','-b','feature')
(repo/'README.md').write_text('Synthetic attachment demonstration with media\n')
git('add','.')
git('-c','user.name=Scenario','-c','user.email=scenario@example.invalid','commit','-m','Demo change')
git('-c','credential.helper='+helper,'push','origin','feature')
pr=request(api+'/pullrequests?api-version=7.1','POST',json.dumps({'sourceRefName':'refs/heads/feature','targetRefName':'refs/heads/main','title':'Repro attachments','description':'Demo of the change.'}).encode())
pid=pr['pullRequestId']
urls={}
for name in ['demo.gif','demo.mp4']:
    attachment=request(f'{api}/pullRequests/{pid}/attachments/{name}?api-version=7.1-preview.1','POST',(root/name).read_bytes(),'application/octet-stream')
    urls[name]=attachment['url']
description=f"Demo of the change.\n\n[![demo.gif]({urls['demo.gif']})]({urls['demo.mp4']})\n\n[demo.mp4]({urls['demo.mp4']})"
description+='\n\n### Cross-forge image regression checks\n\n![GitHub image](https://raw.githubusercontent.com/pingdotgg/t3code/a35fd811749c2b65d917652cbdb90b28d65b2e0c/assets/prod/t3-black-web-apple-touch-180.png)\n\n![GitLab image](https://gitlab.com/gitlab-org/gitlab/-/raw/master/app/assets/images/gitlab_logo.png)'
request(f'{api}/pullrequests/{pid}?api-version=7.1','PATCH',json.dumps({'description':description}).encode())
state={'pr':pid,'remote':remote,'url':f'{remote}/pullrequest/{pid}','repositoryId':rid,'api':api,'attachments':urls}
(root/'fixture.json').write_text(json.dumps(state))
print('Created synthetic PR',pid)
