"""Seed a real local Forgejo, already running with TLS, for the SSH alias proof.
Usage: python seed-forgejo.py <scratch-directory>
Requires the real forgejo executable, app.ini, and tls.crt in that directory.
Creates only synthetic owner/repo data. The generated token stays in a local file.
"""
import base64, json, secrets, ssl, subprocess, sys, urllib.request
from pathlib import Path
root = Path(sys.argv[1]).resolve()
password = secrets.token_urlsafe(24)
result = subprocess.run([str(root/'forgejo'), '--config', str(root/'app.ini'), 'admin', 'user', 'create', '--username', 'owner', '--password', password, '--email', 'owner@example.invalid', '--admin', '--must-change-password=false'], capture_output=True, text=True)
if result.returncode:
    raise RuntimeError('Could not create synthetic Forgejo owner')
context = ssl.create_default_context(cafile=str(root/'tls.crt'))
def request(path, body, token=None):
    auth = 'token '+token if token else 'Basic '+base64.b64encode(('owner:'+password).encode()).decode()
    req = urllib.request.Request('https://localhost:3443/api/v1/'+path, data=json.dumps(body).encode(), headers={'Authorization':auth,'Content-Type':'application/json'})
    return json.load(urllib.request.urlopen(req, context=context))
token = request('users/owner/tokens', {'name':'alias-proof', 'scopes':['all']})['sha1']
(root/'token').write_text(token)
(root/'token').chmod(0o600)
request('user/repos', {'name':'repo','description':'Synthetic SSH alias proof'},token)
for title in ['Alias issue one','Alias issue two']:
    request('repos/owner/repo/issues', {'title':title,'body':'Synthetic issue for SSH alias login proof.'}, token)
print('Seeded owner/repo with two issues on real Forgejo; token stored locally.')
