#!/usr/bin/env python3
"""Create the real GitLab fixture used by upstream-preservation-proof.e2e.ts.
Requires glab and git authenticated to gitlab.com. No service responses are mocked.
"""
import json, subprocess, tempfile, pathlib, sys

def api(*args):
    return json.loads(subprocess.check_output(['glab', 'api', *args], text=True))

name = sys.argv[1] if len(sys.argv) > 1 else 'upstream-race-proof-47593-r2'
project = api('-X', 'POST', 'projects', '-f', f'name={name}', '-f', 'visibility=private', '-f', 'initialize_with_readme=true')
with tempfile.TemporaryDirectory(prefix='upstream-proof-') as directory:
    repo = pathlib.Path(directory) / 'repo'
    subprocess.run(['git', 'clone', project['http_url_to_repo'], str(repo)], check=True)
    def git(*args):
        subprocess.run(['git', *args], cwd=repo, check=True)
    git('-c', 'user.name=Evidence', '-c', 'user.email=evidence@example.invalid', 'commit', '--allow-empty', '-m', 'Merge request evidence')
    git('push', 'origin', 'HEAD:mr-source', 'origin/main:other-branch')
mr = api('-X', 'POST', f"projects/{project['id']}/merge_requests", '-f', 'source_branch=mr-source', '-f', 'target_branch=main', '-f', 'title=Upstream preservation evidence')
print(json.dumps({'projectId': project['id'], 'repository': project['path_with_namespace'], 'mergeRequest': mr['iid']}))
