"""Create synthetic real GitLab data for the refresh race scenario.
Run with a scratch directory and a unique project name; glab must be signed in.
Use the returned repository URL and merge request number in the scenario.
Delete the project through GitLab after capturing evidence.
"""
import json
import pathlib
import subprocess
import sys

workspace = pathlib.Path(sys.argv[1]).resolve()
workspace.mkdir(parents=True, exist_ok=True)
name = sys.argv[2]
def command(*args):
    return subprocess.check_output(args, cwd=workspace, text=True).strip()
project = json.loads(command('glab', 'api', '-X', 'POST', 'projects', '-f', f'name={name}', '-f', 'visibility=private'))
def git(*args):
    return command('git', *args)
git('init', '-b', 'main')
git('config', 'user.name', 'Scenario')
git('config', 'user.email', 'scenario@example.invalid')
(workspace / 'file.txt').write_text('original\n')
git('add', '.')
git('commit', '-m', 'Original')
git('switch', '-c', 'review-source')
(workspace / 'file.txt').write_text('changed by merge request\n')
git('commit', '-am', 'Changes for review')
git('remote', 'add', 'origin', project['http_url_to_repo'])
git('push', 'origin', 'main', 'review-source')
mr = json.loads(command('glab', 'api', '-X', 'POST', f"projects/{project['id']}/merge_requests", '-f', 'source_branch=review-source', '-f', 'target_branch=main', '-f', 'title=Changes for review'))
print(json.dumps({'projectId': project['id'], 'remote': project['http_url_to_repo'], 'mergeRequest': mr['iid']}))
