"""
Onno Modz — login code helper.

Reads your local Pixel Gun 3D credentials from the Windows registry and prints
a login code to paste into the Onno Modz dashboard. The credentials are stored
as UTF-8 bytes under HKCU\\Software\\Pixel Gun Team\\Pixel Gun 3D.

    AccountCreated* -> player id
    terceShtuA*     -> auth secret
    sufComIndxKey*  -> device id

The code is base64url("<player_id>:<secret>:<device_id>").
Run:  python logincode.py
"""
import base64
import sys
import winreg

REG_PATH = r"Software\Pixel Gun Team\Pixel Gun 3D"


def reg_read(prefix):
    try:
        key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH)
    except FileNotFoundError:
        return None
    i = 0
    while True:
        try:
            name, value, _ = winreg.EnumValue(key, i)
            if name.startswith(prefix) and isinstance(value, bytes):
                return value.decode("utf-8", errors="ignore").rstrip("\x00")
            i += 1
        except OSError:
            return None


def build_code(pid, secret, device):
    raw = f"{pid}:{secret}:{device}".encode("utf-8")
    return base64.urlsafe_b64encode(raw).decode().rstrip("=")


def main():
    pid = reg_read("AccountCreated")
    secret = reg_read("terceShtuA")
    device = reg_read("sufComIndxKey")
    if not all((pid, secret, device)):
        print("Could not find Pixel Gun 3D credentials in the registry.")
        print("Launch the game at least once, then run this again.")
        return 1

    code = build_code(pid, secret, device)
    print("player_id  :", pid)
    print("login code :", code)
    try:
        import subprocess
        subprocess.run(["clip"], input=code.encode("utf-8"), check=True)
        print("(copied to clipboard)")
    except Exception:
        pass
    return 0


if __name__ == "__main__":
    sys.exit(main())