"""
User accounts.
  * data/users.json: username -> salted PBKDF2 password hash, created time, disabled flag, owner flag
  * The owner is the account from .env (DASHBOARD_USER / DASHBOARD_PASSWORD), created on first start
  * Anyone can sign up (unless SIGNUP=off); each account gets its own bot, wallet and history
  * KeyBox encrypts every user's Aster API wallet key on disk (AES-GCM, key in data/secret.key)
"""
import base64
import hashlib
import hmac
import json
import os
import re
import secrets
import threading
import time

from Crypto.Cipher import AES

NAME_RE = re.compile(r"^[a-z0-9_]{3,20}$")
ITER = 200_000


def _hash(password, salt=None):
    salt = salt or secrets.token_hex(16)
    h = hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), ITER).hex()
    return f"pbkdf2${ITER}${salt}${h}"


def _check(password, stored):
    try:
        _, it, salt, h = stored.split("$")
        got = hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), int(it)).hex()
        return hmac.compare_digest(got, h)
    except (ValueError, AttributeError):
        return False


def _write_json(path, data):
    tmp = path + ".tmp"
    with open(tmp, "w") as f:
        json.dump(data, f, indent=1)
    os.chmod(tmp, 0o600)
    os.replace(tmp, path)


class Users:
    def __init__(self, data_dir, owner, owner_password, max_users=200):
        self.path = os.path.join(data_dir, "users.json")
        self.lock = threading.Lock()
        self.owner = owner.strip().lower()
        self.max_users = max_users
        try:
            with open(self.path) as f:
                self.u = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            self.u = {}
        if self.owner not in self.u:
            self.u[self.owner] = {"pw": _hash(owner_password), "created": time.time(), "disabled": False}
        self.u[self.owner]["owner"] = True
        self.u[self.owner]["disabled"] = False
        _write_json(self.path, self.u)

    def names(self):
        return list(self.u)

    def get(self, name):
        return self.u.get((name or "").strip().lower())

    def is_owner(self, name):
        return (name or "").lower() == self.owner

    def active(self, name):
        u = self.get(name)
        return bool(u) and not u.get("disabled")

    def verify(self, name, password):
        u = self.get(name)
        if not u:
            _check(password, _hash("x"))          # same time either way, so names can't be probed
            return None
        return (name or "").strip().lower() if _check(password or "", u["pw"]) else None

    def create(self, name, password):
        name = (name or "").strip().lower()
        if not NAME_RE.match(name):
            raise ValueError("Username: 3 to 20 characters, using only letters, numbers and _")
        if len(password or "") < 8:
            raise ValueError("Password: at least 8 characters")
        if password.lower() == name:
            raise ValueError("The password can't be the same as the username")
        with self.lock:
            if name in self.u:
                raise ValueError("That username is taken. Choose another one.")
            if len(self.u) >= self.max_users:
                raise ValueError("Sign-up is full right now. Contact the owner of this bot.")
            self.u[name] = {"pw": _hash(password), "created": time.time(), "disabled": False}
            _write_json(self.path, self.u)
        return name

    def set_password(self, name, old, new):
        if not self.verify(name, old):
            raise ValueError("Current password is wrong")
        if len(new or "") < 8:
            raise ValueError("New password: at least 8 characters")
        with self.lock:
            self.u[name]["pw"] = _hash(new)
            _write_json(self.path, self.u)

    def set_disabled(self, name, disabled):
        name = (name or "").lower()
        if name == self.owner:
            raise ValueError("The owner account can't be disabled")
        if name not in self.u:
            raise ValueError("No such user")
        with self.lock:
            self.u[name]["disabled"] = bool(disabled)
            _write_json(self.path, self.u)


class KeyBox:
    """Encrypts API wallet keys before they are written to disk."""

    def __init__(self, data_dir):
        path = os.path.join(data_dir, "secret.key")
        if not os.path.exists(path):
            fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
            with os.fdopen(fd, "wb") as f:
                f.write(secrets.token_bytes(32))
        with open(path, "rb") as f:
            self.k = f.read()

    def seal(self, text):
        nonce = secrets.token_bytes(12)
        c = AES.new(self.k, AES.MODE_GCM, nonce=nonce)
        ct, tag = c.encrypt_and_digest(text.encode())
        return base64.b64encode(nonce + tag + ct).decode()

    def open(self, blob):
        raw = base64.b64decode(blob)
        c = AES.new(self.k, AES.MODE_GCM, nonce=raw[:12])
        return c.decrypt_and_verify(raw[28:], raw[12:28]).decode()
