#!/usr/bin/env python3
"""
Register a user on Matrix server using shared secret
"""
import hmac
import hashlib
import json
import requests

# Get nonce
nonce_response = requests.get("http://localhost:8008/_synapse/admin/v1/register")
nonce = nonce_response.json()["nonce"]

print(f"Got nonce: {nonce[:20]}...")

# Registration details
username = "einszwovier"
password = "einszwo4"
admin = False
shared_secret = "D2mw3LqNKe98ga-pYO1l5KbXf^jgx&s5yjq&ipAGjln:AzLag8"

# Generate MAC
mac = hmac.new(
    key=shared_secret.encode('utf8'),
    digestmod=hashlib.sha1,
)

mac.update(nonce.encode('utf8'))
mac.update(b"\x00")
mac.update(username.encode('utf8'))
mac.update(b"\x00")
mac.update(password.encode('utf8'))
mac.update(b"\x00")
mac.update(b"notadmin" if not admin else b"admin")

mac_str = mac.hexdigest()

# Register user
data = {
    "nonce": nonce,
    "username": username,
    "password": password,
    "admin": admin,
    "mac": mac_str
}

response = requests.post(
    "http://localhost:8008/_synapse/admin/v1/register",
    json=data
)

print(f"\nRegistration response: {response.status_code}")
print(json.dumps(response.json(), indent=2))

if response.status_code == 200:
    print(f"\n✅ User registered successfully!")
    print(f"User ID: {response.json()['user_id']}")
    print(f"Access Token: {response.json()['access_token']}")
else:
    print(f"\n❌ Registration failed")
