import pathlib,re,json,urllib.request,urllib.error,http.cookiejar,sys,datetime
side=sys.argv[1]
root=pathlib.Path(__file__).parent
work=pathlib.Path(sys.argv[2])
log=(root/('base-server.log' if side=='before' else 'head-server.log')).read_text()
port=re.search(r'serverPort=(\d+)',log)[1]
token=re.search(r'pairingUrl: .*#token=(\w+)',log)[1]
jar=http.cookiejar.CookieJar(); client=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
origin=f'http://127.0.0.1:{port}'
def request(path,data=None):
    req=urllib.request.Request(origin+path,data=json.dumps(data).encode() if data is not None else None,headers={'Content-Type':'application/json'})
    try:
        with client.open(req) as r: return r.status,json.load(r)
    except urllib.error.HTTPError as e: return e.code,json.load(e)
status,_=request('/api/auth/browser-session',{'credential':token})
assert status==200,status
out=[]
def show(label,result):
    status,body=result
    # Keep only synthetic account identity and the fields relevant to the bug.
    if label.startswith('GET'):
        body={k:body.get(k) for k in ('linked','cloudUserId','linkRevoked')}
    out.extend([label,f'HTTP {status}',json.dumps(body,indent=2)])
def link(account):
    return request('/api/connect/relay-config',{'relayUrl':'https://relay.example.test','cloudUserId':account,'environmentCredential':f'cred-{account}','cloudMintPublicKey':'-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAqZ2u2LjMoAyG2QTHXmITJ9w6RzZtVUAv394XCcPV0zE=\n-----END PUBLIC KEY-----','endpointRuntime':None})
out.extend([f'{side.upper()}: real development server; fresh isolated database; synthetic accounts',f'Commit: {sys.argv[3]}','Authenticated through POST /api/auth/browser-session (credential omitted).'])
show('POST /api/connect/relay-config: account-a',link('account-a'))
show('GET /api/connect/link-state',request('/api/connect/link-state'))
secrets=list((work/'.t3').rglob('cloud-linked-user-id.bin'))
assert len(secrets)==1,secrets
(secrets[0].parent/'cloud-link-revoked.bin').write_text('true')
out.append("Simulate relay revocation: write cloud-link-revoked = 'true' (same mark as markLinkRevoked).")
show('GET /api/connect/link-state after revocation',request('/api/connect/link-state'))
show('POST /api/connect/relay-config: account-b',link('account-b'))
show('GET /api/connect/link-state after relink',request('/api/connect/link-state'))
out.append('Stored account: '+secrets[0].read_text())
run=root/(side+'-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'));run.mkdir()
(run/'transcript.txt').write_text('\n\n'.join(out)+'\n')
print('\n\n'.join(out))
print('Saved:',run/'transcript.txt')
