import json,urllib.request,base64,subprocess,os,pathlib
ROOT='http://127.0.0.1:14935'
def api(user,method,path,data=None):
    auth=base64.b64encode((user+':'+os.environ['PROOF_PASSWORD']).encode()).decode()
    req=urllib.request.Request(ROOT+'/api/v1/'+path,data=json.dumps(data).encode() if data is not None else None,headers={'Authorization':'Basic '+auth,'Content-Type':'application/json'},method=method)
    with urllib.request.urlopen(req) as r:return json.load(r)
api('maria','POST','user/repos',{'name':'project','auto_init':True,'default_branch':'main'})
for user in ['Alice','Bob']:
    api(user,'POST','repos/maria/project/forks',{'name':'project'})
    api(user,'POST',f'repos/{user}/project/branches',{'new_branch_name':'feature','old_branch_name':'main'})
    api(user,'POST',f'repos/{user}/project/contents/{user}.txt',{'branch':'feature','message':f'{user} feature','content':base64.b64encode(f'{user} feature\n'.encode()).decode()})
    pr=api(user,'POST','repos/maria/project/pulls',{'head':f'{user}:feature','base':'main','title':f'{user} feature'})
    if user=='Bob':
        for i in range(20):
            api(user,'PATCH',f'repos/maria/project/pulls/{pr["number"]}',{'state':'closed'})
            pr=api(user,'POST','repos/maria/project/pulls',{'head':'Bob:feature','base':'main','title':f'Bob feature {i+3}'})
token=api('Alice','POST','users/Alice/tokens',{'name':'proof','scopes':['all']})['sha1']
open(pathlib.Path(__file__).with_name('token'),'w').write(token)
print('Seeded Alice PR #1 and 21 newer Bob PRs, with #22 open.')
