"""
Wallet connection:
  * SafePal address  -> read-only USDT/BNB balance straight from BNB Chain (no keys needed)
  * Aster API wallet -> the bot's trading key (can trade, cannot withdraw); stored encrypted on the server
"""
import json
import os
import threading
import time

import requests

from .signer import address_of, is_address, checksum

BSC_RPCS = ["https://bsc-dataseed.bnbchain.org", "https://bsc-dataseed1.defibit.io", "https://bsc.publicnode.com"]
USDT_BEP20 = "0x55d398326f99059fF775485246999027B3197955"   # 18 decimals


class Credentials:
    def __init__(self, data_dir, env_user="", env_signer="", env_key="", box=None):
        self.path = os.path.join(data_dir, "credentials.json")
        self.box = box
        # .env values are used only if they are real, valid wallet details (placeholders are ignored)
        self.user = self.signer = self.key = ""
        try:
            if is_address(env_user) and is_address(env_signer) and env_key \
                    and address_of(env_key).lower() == env_signer.lower():
                self.user, self.signer, self.key = checksum(env_user), checksum(env_signer), env_key
        except ValueError:
            pass
        try:
            with open(self.path) as f:
                d = json.load(f)
            if is_address(d.get("user", "")):
                key = d.get("key", "")
                if d.get("key_enc") and box:
                    key = box.open(d["key_enc"])
                self.user, self.signer, self.key = d.get("user", ""), d.get("signer", ""), key
                if d.get("key") and box:
                    self.save(self.user, self.signer, self.key)       # older plain file: encrypt it now
        except (FileNotFoundError, json.JSONDecodeError):
            pass

    @property
    def has_api(self):
        return bool(self.user and self.signer and self.key)

    def validate(self, user, signer, key):
        user, signer, key = user.strip(), signer.strip(), key.strip()
        if not is_address(user):
            raise ValueError("Your SafePal (main) wallet address must start with 0x and be 42 characters long")
        if not is_address(signer):
            raise ValueError("The API wallet address must start with 0x and be 42 characters long")
        if user.lower() == signer.lower():
            raise ValueError("The API wallet address must be the new API wallet from Aster, not your SafePal address")
        if address_of(key).lower() != signer.lower():
            raise ValueError("This private key does not belong to that API wallet address. Copy both again from Aster.")
        return checksum(user), checksum(signer), key if key.startswith("0x") else "0x" + key

    def save(self, user, signer, key):
        self.user, self.signer, self.key = user, signer, key
        tmp = self.path + ".tmp"
        with open(tmp, "w") as f:
            if self.box:
                json.dump({"user": user, "signer": signer, "key_enc": self.box.seal(key)}, f)
            else:
                json.dump({"user": user, "signer": signer, "key": key}, f)
        os.chmod(tmp, 0o600)
        os.replace(tmp, self.path)

    def save_address_only(self, user):
        self.user, self.signer, self.key = user, "", ""
        tmp = self.path + ".tmp"
        with open(tmp, "w") as f:
            json.dump({"user": user}, f)
        os.chmod(tmp, 0o600)
        os.replace(tmp, self.path)

    def clear(self):
        self.user = self.signer = self.key = ""
        try:
            os.remove(self.path)
        except FileNotFoundError:
            pass


def _rpc(method, params):
    last = None
    for url in BSC_RPCS:
        try:
            r = requests.post(url, json={"jsonrpc": "2.0", "id": 1, "method": method, "params": params}, timeout=6)
            j = r.json()
            if "result" in j:
                return j["result"]
            last = j.get("error")
        except Exception as e:
            last = e
    raise RuntimeError(f"BNB Chain not reachable ({last})")


def chain_balances(address):
    """USDT (BEP20) and BNB held directly in the wallet on BNB Chain."""
    data = "0x70a08231" + "0" * 24 + address.lower()[2:]
    usdt = int(_rpc("eth_call", [{"to": USDT_BEP20, "data": data}, "latest"]), 16) / 1e18
    bnb = int(_rpc("eth_getBalance", [address, "latest"]), 16) / 1e18
    return usdt, bnb


class WalletWatcher:
    """Refreshes the SafePal on-chain balance in the background (every 60 s)."""

    def __init__(self):
        self.address = ""
        self.result = None
        self.error = None
        self.updated = 0
        self._lock = threading.Lock()
        threading.Thread(target=self._loop, daemon=True).start()

    def set_address(self, address):
        with self._lock:
            if address != self.address:
                self.address, self.result, self.error, self.updated = address, None, None, 0

    def _loop(self):
        while True:
            addr = self.address
            if addr and time.time() - self.updated > 60:
                try:
                    usdt, bnb = chain_balances(addr)
                    with self._lock:
                        if addr == self.address:
                            self.result, self.error = {"usdt": usdt, "bnb": bnb}, None
                except Exception as e:
                    self.error = str(e)
                self.updated = time.time()
            time.sleep(2)

    def refresh_now(self):
        self.updated = 0
