import base64, json, os, ssl, subprocess, sys, urllib.request
from pathlib import Path
root = Path(sys.argv[1]).resolve()
ctx = ssl.create_default_context(cafile=str(root / 'ca.pem'))
env = {**os.environ, 'XDG_DATA_HOME': str(root / 'data'), 'SSL_CERT_FILE': str(root / 'ca.pem')}
auth = 'Basic ' + base64.b64encode(b'proof-user:ProofOnly-38048-Local').decode()
def api(port, path, data=None, method=None):
    req = urllib.request.Request(f'https://127.0.0.1:{port}/api/v1{path}', data=json.dumps(data).encode() if data else None, method=method, headers={'Authorization': auth, 'Content-Type':'application/json'})
    with urllib.request.urlopen(req, context=ctx) as r:
        body = r.read()
        return json.loads(body) if body else None
keys = root / 'data/forgejo-cli/keys.json'
keys.parent.mkdir(parents=True, exist_ok=True)
keys.write_text(json.dumps({'hosts': {}, 'aliases': {}}))
for port in [18441,18442]:
    subprocess.run([str(root/'fj'), '--host', f'https://127.0.0.1:{port}', 'auth', 'logout'], env=env, cwd=root, capture_output=True)
    for old in api(port, '/users/proof-user/tokens'):
        api(port, f"/users/proof-user/tokens/{old['id']}", method='DELETE')
    token = api(port, '/users/proof-user/tokens', {'name':'discovery-proof', 'scopes':['all']})
    result = subprocess.run([str(root/'fj'), '--host', f'https://127.0.0.1:{port}', 'auth','add-token'], input=token['sha1'], text=True, env=env, capture_output=True, cwd=root)
    if result.returncode:
        raise RuntimeError(result.stderr)
    if port == 18441:
        api(port, f"/users/proof-user/tokens/{token['id']}", method='DELETE')
lines=[]
for port in [18441,18442]:
    cmd=[str(root/'fj'),'--host',f'https://127.0.0.1:{port}','whoami']
    r=subprocess.run(cmd,capture_output=True,text=True,env=env,cwd=root)
    lines += [f'$ fj --host https://127.0.0.1:{port} whoami', f'exit {r.returncode}',r.stdout.strip(),r.stderr.strip()]
transcript='\n'.join(lines)+'\n'
(root/'login-preflight.txt').write_text(transcript)
print(transcript)
