"""
One bot per user. Each user has their own folder (data/users/<name>/) with their paper and live
history, their wallet connection and their chosen mode, and their own background thread.
All bots share one price feed (wave/market.py).
"""
import json
import logging
import os
import shutil
import threading
import time

from .aster_spot import AsterSpot
from .exchange import PaperExchange, LiveExchange
from .engine import WaveEngine, STOPPED
from .accounts import Credentials, WalletWatcher

log = logging.getLogger("bots")


class UserBot:
    """A user's active engine (paper or live), wallet connection and background loop."""

    def __init__(self, name, cfg, market, box, data_dir, env_creds=("", "", "")):
        self.name, self.cfg, self.mk = name, cfg, market
        self.dir = data_dir
        os.makedirs(self.dir, exist_ok=True)
        self.mode_file = os.path.join(self.dir, "mode.json")
        self.lock = threading.RLock()
        self.creds = Credentials(self.dir, *env_creds, box=box)
        self.wallet = None
        if self.creds.user:
            self._watch(self.creds.user)
        self.aster_error = None
        self.aster_bal = None
        self._aster_t = 0
        self.disabled = False
        try:
            with open(self.mode_file) as f:
                mode = json.load(f)["mode"]
        except (FileNotFoundError, json.JSONDecodeError, KeyError):
            mode = "paper"
        if mode == "live" and not self.creds.has_api:
            mode = "paper"
        try:
            self.engine = self._make(mode)
        except Exception as e:
            log.error("[%s] live mode could not start (%s) - falling back to paper", name, e)
            self.engine = self._make("paper")
            self.engine.event(f"Live mode could not start: {e}. Running in paper mode.", "error")

    def _watch(self, address):
        if not self.wallet:
            self.wallet = WalletWatcher()
        self.wallet.set_address(address)

    def client(self, with_key):
        c = self.creds
        return AsterSpot(self.cfg.spot_url, self.cfg.chain_id, c.user, c.signer, c.key if with_key else "")

    def _make(self, mode):
        def factory(state):
            if mode == "live":
                return LiveExchange(self.cfg, self.client(True), state)
            return PaperExchange(self.cfg, self.client(False), state, market=self.mk)
        eng = WaveEngine(self.cfg, factory, os.path.join(self.dir, mode), market=self.mk, name=self.name)
        with open(self.mode_file, "w") as f:
            json.dump({"mode": mode}, f)
        return eng

    @property
    def mode(self):
        return "live" if self.engine.ex.is_live else "paper"

    def switch(self, mode):
        with self.lock:
            if mode == self.mode:
                return
            if self.engine.s["status"] != STOPPED:
                raise ValueError("Stop the bot first (Pause or Sell all), then switch mode")
            if mode == "live" and not self.creds.has_api:
                raise ValueError("Connect your Aster API wallet first")
            new = self._make(mode)
            self.engine = new
            new.event(f"Switched to {mode.upper()} mode." + (" Real money from here on." if mode == "live" else ""), "info")

    def aster_balances(self, force=False):
        """Real Aster spot balance (needs the API wallet). Cached 20 s."""
        if not self.creds.has_api:
            return None
        if force or time.time() - self._aster_t > 20:
            self._aster_t = time.time()
            try:
                b = self.client(True).balances()
                self.aster_bal = {"usdt": b.get(self.cfg.quote_asset, 0.0), "bnb": b.get(self.cfg.base_asset, 0.0)}
                self.aster_error = None
            except Exception as e:
                self.aster_error = str(e)
        return self.aster_bal

    # ------------------------------------------------------------- wallet connection
    def connect_address(self, address):
        from .signer import is_address, checksum
        a = (address or "").strip()
        if not is_address(a):
            raise ValueError("A wallet address starts with 0x and is 42 characters long")
        self._no_wallet_change_in_live()
        self.creds.save_address_only(checksum(a))
        self._watch(self.creds.user)

    def connect_api(self, user, signer, key):
        self._no_wallet_change_in_live()
        user, signer, key = self.creds.validate(user, signer, key)
        test = AsterSpot(self.cfg.spot_url, self.cfg.chain_id, user, signer, key)
        try:
            b = test.balances()          # proves Aster accepts the API wallet
        except Exception as e:
            raise ValueError(f"Aster did not accept this API wallet: {e}. Check that it is authorized "
                             f"for spot trading, that its IP list includes this server, and that the account "
                             f"has made a deposit.")
        self.creds.save(user, signer, key)
        self._watch(user)
        self.aster_bal = {"usdt": b.get(self.cfg.quote_asset, 0.0), "bnb": b.get(self.cfg.base_asset, 0.0)}
        self.aster_error, self._aster_t = None, time.time()

    def disconnect(self):
        self._no_wallet_change_in_live()
        self.creds.clear()
        if self.wallet:
            self.wallet.set_address("")
        self.aster_bal = None

    def _no_wallet_change_in_live(self):
        if self.mode == "live":
            raise ValueError("Switch to paper mode before changing the wallet")

    # ------------------------------------------------------------- background loop
    def loop(self):
        if self.engine.s["status"] != STOPPED:
            self.engine.event(f"Resumed after restart ({self.engine.s['status']}).", "info")
        while True:
            t0 = time.time()
            eng = self.engine
            try:
                eng.tick()                # a disabled account's bot is paused, so this only follows prices
            except Exception as e:
                eng.last_error = str(e)
                log.exception("[%s] tick", self.name)
            time.sleep(max(0.2, self.cfg.tick_seconds - (time.time() - t0)))


class Bots:
    """All users' bots. Every account's bot is started when the program starts (so open hooks keep
    selling while nobody is signed in) and new accounts get theirs on sign-up."""

    def __init__(self, cfg, market, box, users):
        self.cfg, self.mk, self.box, self.users = cfg, market, box, users
        self.lock = threading.Lock()
        self.b = {}
        self.root = os.path.join(cfg.data_dir, "users")
        os.makedirs(self.root, exist_ok=True)
        self._move_owner_data()

    def _move_owner_data(self):
        """Older single-user versions kept everything directly in data/. That becomes the owner's bot."""
        d = self.cfg.data_dir
        dest = os.path.join(self.root, self.users.owner)
        if os.path.exists(dest):
            return
        os.makedirs(dest)
        for f in ("paper", "live", "credentials.json", "mode.json"):
            src = os.path.join(d, f)
            if os.path.exists(src):
                shutil.move(src, os.path.join(dest, f))
                log.info("moved %s to %s", src, dest)

    def get(self, name):
        name = (name or "").lower()
        with self.lock:
            bot = self.b.get(name)
            if bot is None:
                env = (self.cfg.user_address, self.cfg.signer_address, self.cfg.signer_private_key) \
                    if self.users.is_owner(name) else ("", "", "")
                bot = UserBot(name, self.cfg, self.mk, self.box, os.path.join(self.root, name), env)
                bot.disabled = not self.users.active(name)
                self.b[name] = bot
                threading.Thread(target=bot.loop, daemon=True, name=f"bot-{name}").start()
            return bot

    def start_all(self):
        for name in self.users.names():
            try:
                self.get(name)
            except Exception:
                log.exception("could not start the bot of %s", name)

    def set_disabled(self, name, disabled):
        self.users.set_disabled(name, disabled)
        bot = self.get(name)
        if disabled:
            with bot.engine.lock:
                if bot.engine.s["status"] != STOPPED:
                    bot.engine.stop("stop")
                bot.engine.event("Account disabled by the owner. Bot paused; open hooks are kept.", "warn")
        else:
            bot.engine.event("Account enabled again by the owner. Press Resume to continue trading.", "info")
        bot.disabled = disabled

    def summary(self):
        out = []
        for name in self.users.names():
            u = self.users.get(name)
            bot = self.b.get(name)
            row = {"name": name, "created": u.get("created"), "disabled": bool(u.get("disabled")),
                   "owner": bool(u.get("owner"))}
            if bot:
                e = bot.engine
                with e.lock:
                    row.update(mode=bot.mode, status=e.s["status"], hooks=len(e.s["lots"]),
                               profit=sum(w["profit"] for w in e.waves),
                               wallet=bot.creds.has_api)
            out.append(row)
        return out
