import subprocess,json,time,pathlib
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('--output-dir',default='.')
out=pathlib.Path(parser.parse_args().output_dir)
out.mkdir(parents=True,exist_ok=True)
def api(path,method='GET',data=None):
 args=['glab','api',path,'--method',method]
 if data is not None: args+=['--input','-']
 p=subprocess.run(args,input=json.dumps(data) if data is not None else None,text=True,capture_output=True,check=True)
 return json.loads(p.stdout) if p.stdout else None
p=api('projects','POST',{'name':'resolved-toggle-proof-'+str(int(time.time())),'visibility':'private','initialize_with_readme':True})
(out/'fixture.json').write_text(json.dumps({'projectId':p['id'],'scope':p['path_with_namespace']}))
id=p['id']
api(f'projects/{id}/repository/commits','POST',{'branch':'review-change','start_branch':p['default_branch'],'commit_message':'Add review example','actions':[{'action':'create','file_path':'example.txt','content':'A small change to review.\n'}]})
mr=api(f'projects/{id}/merge_requests','POST',{'source_branch':'review-change','target_branch':p['default_branch'],'title':'Keep the resolved toggle under the cursor','description':'Synthetic review discussion for a pointer interaction.'})
refs=mr.get('diff_refs')
if not refs:
 time.sleep(2)
 mr=api(f'projects/{id}/merge_requests/1'); refs=mr['diff_refs']
d=api(f'projects/{id}/merge_requests/1/discussions','POST',{'body':'Please keep this review discussion resolved.','position':{'position_type':'text','base_sha':refs['base_sha'],'start_sha':refs['start_sha'],'head_sha':refs['head_sha'],'new_path':'example.txt','old_path':'example.txt','new_line':1}})
api(f'projects/{id}/merge_requests/1/discussions/{d["id"]}/notes','POST',{'body':'The change is ready for review.'})
api(f'projects/{id}/merge_requests/1/discussions/{d["id"]}','PUT',{'resolved':True})
fixture={'projectId':id,'scope':p['path_with_namespace'],'discussionId':d['id'],'url':mr['web_url']}
(out/'fixture.json').write_text(json.dumps(fixture))
print(json.dumps(fixture))
