#!/usr/bin/env python3
"""Seed the local Forgejo 11 fixture; pass an empty fixture directory as argv[1]."""
import base64
import json
import os
from pathlib import Path
import secrets
import subprocess
import sys
import urllib.request

fixture = Path(sys.argv[1]).resolve()
fixture.mkdir(parents=True, exist_ok=True)
password = secrets.token_urlsafe(24)
container = 'proof-40490-forgejo'
subprocess.run(['docker', 'exec', '--user', 'git', container, 'forgejo', 'admin', 'user', 'create', '--username', 'fjadmin', '--password', password, '--email', 'scenario@example.invalid', '--admin', '--must-change-password=false'], check=True, stdout=subprocess.DEVNULL)
auth = 'Basic ' + base64.b64encode(('fjadmin:' + password).encode()).decode()
def post(path, data):
    request = urllib.request.Request('http://127.0.0.1:13987/api/v1' + path, data=json.dumps(data).encode(), headers={'Authorization': auth, 'Content-Type': 'application/json'})
    return json.load(urllib.request.urlopen(request))
token = post('/users/fjadmin/tokens', {'name': 'proof40490', 'scopes': ['all']})['sha1']
subprocess.run([str(fixture / 'tea'), 'login', 'add', '--name', 'proof', '--url', 'http://127.0.0.1:13987', '--token', token], env={**os.environ, 'XDG_CONFIG_HOME': str(fixture / 'config')}, check=True, stdout=subprocess.DEVNULL)
post('/user/repos', {'name': 'demo', 'auto_init': True, 'default_branch': 'main'})
post('/repos/fjadmin/demo/branches', {'new_branch_name': 'feature', 'old_branch_name': 'main'})
post('/repos/fjadmin/demo/contents/feature.txt', {'branch': 'feature', 'content': base64.b64encode(b'Feature content\n').decode(), 'message': 'Add feature file'})
post('/repos/fjadmin/demo/pulls', {'base': 'main', 'head': 'feature', 'title': 'Add feature file', 'body': 'This pull request adds the feature file. Older clients should still show this description.'})
print('Synthetic Forgejo fixture ready')
