"""Synthetic GitLab seed used for the mobile cancelled-checks proof.
Requires glab authentication. Creates a disposable private project and open MR.
"""
import json
import subprocess
import time


def post(endpoint, **body):
    return json.loads(subprocess.check_output(
        ['glab', 'api', '-X', 'POST', endpoint, '--input', '-'],
        input=json.dumps(body).encode()))


project = post('projects', name=f'cancelled-checks-proof-{int(time.time())}',
               visibility='private', initialize_with_readme=True)
prefix = f"projects/{project['id']}/"
post(prefix + 'repository/branches', branch='feature', ref='main')
commit = post(prefix + 'repository/commits', branch='feature',
              commit_message='Add deployment example', actions=[{
                  'action': 'create', 'file_path': 'deploy.txt',
                  'content': 'Synthetic deployment example\n'}])
post(prefix + 'merge_requests', source_branch='feature', target_branch='main',
     title='Deployment checks example')
for name, states in [('build', ['running', 'success']), ('deploy', ['running', 'canceled'])]:
    for state in states:
        post(prefix + 'statuses/' + commit['id'], state=state, name=name, ref='feature')
print(json.dumps({'projectId': project['id'], 'cloneUrl': project['http_url_to_repo'],
                  'headSha': commit['id']}))
