"""
Two exchanges with the same interface:
  PaperExchange - simulated wallet, real Aster prices (or a demo price feed). Safe for testing.
  LiveExchange  - real orders on Aster spot.
Both return fills already NET of fees: buy -> (bnb_received, usdt_spent, avg_price),
sell -> (usdt_received, avg_price).
"""
import math
import random
import time
import uuid

import requests

from .aster_spot import AsterSpot, AsterError


class OrderStateUnknown(Exception):
    """The order was sent but Aster could not confirm whether it executed. The bot pauses itself."""

    def __init__(self, msg, cid, side):
        super().__init__(msg)
        self.cid, self.side = cid, side


class DemoFeed:
    """Simulated BNB price with waves, for trying the UI when you don't want to wait for the real market."""

    def __init__(self, start=700.0):
        self.p, self.t, self.phase = start, time.time(), 0.0

    def price(self):
        now = time.time()
        steps = max(1, int((now - self.t) / 0.5))
        for _ in range(steps):
            self.phase += 0.003
            drift = 0.00008 * math.sin(self.phase) + 0.00004 * math.sin(self.phase * 3.7)
            self.p *= 1 + drift + random.gauss(0, 0.00028)
        self.t = now
        return round(self.p, 2)


class PaperExchange:
    is_live = False
    note = note_extra = None

    def __init__(self, cfg, client: AsterSpot, state, market=None):
        self.cfg, self.client, self.mk = cfg, client, market
        self.fee = cfg.taker_fee
        self.min_notional, self.step = 5.0, 0.001
        w = state.setdefault("paper_wallet", {})
        w.setdefault(cfg.quote_asset, cfg.paper_start_usdt)
        w.setdefault(cfg.base_asset, 0.0)
        self.w = w
        self.feed = DemoFeed() if cfg.price_feed == "demo" else None
        self._last = None

    def quote(self):
        """(best bid, best ask): the prices a sell / a buy would really get right now."""
        if self.mk:
            self.bid, self.ask = self.mk.quote()
        elif self.feed:
            p = self.feed.price()
            self.bid, self.ask = round(p - 0.01, 2), round(p + 0.01, 2)
        else:
            self.bid, self.ask = self.client.book(self.cfg.symbol)
        self._last = (self.bid + self.ask) / 2
        return self.bid, self.ask

    def market_price(self):
        if self.feed:
            return self._last
        return self.client.futures_price(self.cfg.futures_url, self.cfg.symbol)

    def candle_history(self, limit=1440, interval="1m"):
        if self.feed:
            return []
        try:
            return [[int(k[0]) // 1000, float(k[1]), float(k[2]), float(k[3]), float(k[4])]
                    for k in self.client.futures_klines(self.cfg.futures_url, self.cfg.symbol, interval, limit)]
        except Exception:
            return []

    def history(self):
        if self.feed:
            return []
        try:
            return [(int(k[0]) / 1000, float(k[4])) for k in self.client.klines(self.cfg.symbol, "1m", 360)]
        except Exception:
            return []

    def balances(self):
        return dict(self.w)

    def floor_qty(self, q):
        return math.floor(q / self.step + 1e-9) * self.step

    def buy(self, usdt):
        p = self.ask                              # a buy pays the best ask
        if self.w[self.cfg.quote_asset] + 1e-9 < usdt:
            raise RuntimeError("insufficient USDT")
        qty = usdt / p * (1 - self.fee)          # fee taken from the BNB received (like most exchanges)
        self.w[self.cfg.quote_asset] -= usdt
        self.w[self.cfg.base_asset] += qty
        return qty, usdt, p

    def sell(self, qty):
        p = self.bid                              # a sell gets the best bid
        qty = min(qty, self.w[self.cfg.base_asset])
        usdt = qty * p * (1 - self.fee)
        self.w[self.cfg.base_asset] -= qty
        self.w[self.cfg.quote_asset] += usdt
        return usdt, p, qty

    def deposit(self, amount):
        self.w[self.cfg.quote_asset] += amount


class LiveExchange:
    is_live = True
    note = note_extra = None  # set after an order that needed top-ups or was only partly filled
    TOPUP_TRIES = 3

    def __init__(self, cfg, client: AsterSpot, state):
        self.cfg, self.c = cfg, client
        f = client.load_filters(cfg.symbol)
        self.min_notional, self.step = f["min_notional"], float(f["step"])
        self.fee = client.commission(cfg.symbol) or cfg.taker_fee
        self._last = None

    def quote(self):
        self.bid, self.ask = self.c.book(self.cfg.symbol)
        self._last = (self.bid + self.ask) / 2
        return self.bid, self.ask

    def market_price(self):
        return self.c.futures_price(self.cfg.futures_url, self.cfg.symbol)

    def candle_history(self, limit=1440, interval="1m"):
        try:
            return [[int(k[0]) // 1000, float(k[1]), float(k[2]), float(k[3]), float(k[4])]
                    for k in self.c.futures_klines(self.cfg.futures_url, self.cfg.symbol, interval, limit)]
        except Exception:
            return []

    def history(self):
        try:
            return [(int(k[0]) / 1000, float(k[4])) for k in self.c.klines(self.cfg.symbol, "1m", 360)]
        except Exception:
            return []

    def balances(self):
        return self.c.balances()

    def floor_qty(self, q):
        return self.c.floor_qty(q)

    # ---------------------------------------------------------- safe order placement
    def _place(self, side, qty):
        """Send a market order with our own reference ID. If the reply is lost (timeout, connection drop,
        server error), ask Aster about that ID instead of guessing: found -> use it; confirmed missing ->
        it was never placed; still unknown after ~30 s -> raise OrderStateUnknown (the bot pauses)."""
        cid = f"wave{side[0].lower()}{uuid.uuid4().hex[:20]}"
        try:
            return self.c.market(self.cfg.symbol, side, qty, client_id=cid)
        except AsterError as e:
            if e.status is not None and e.status < 500 and e.status != 408:
                raise                      # a clear rejection (e.g. not enough balance): nothing executed
            first_error = e
        except requests.RequestException as e:
            first_error = e
        confirmed_missing = 0
        for wait in (1, 2, 3, 5, 8, 12):
            time.sleep(wait)
            try:
                o = self.c.get_order(self.cfg.symbol, client_id=cid)
                if o and o.get("orderId") is not None:
                    return o               # it did go through: record it normally
            except AsterError as e:
                if e.code == -2013 or "not exist" in str(e.msg).lower():
                    confirmed_missing += 1
                    if confirmed_missing >= 2 and wait >= 3:
                        raise RuntimeError(f"{side} order was not placed (connection problem: {first_error})")
            except requests.RequestException:
                pass
        raise OrderStateUnknown(f"{side} order {cid}: Aster did not confirm whether it executed ({first_error})",
                                cid, side)

    def check_order(self, cid, side):
        """Ask Aster again about an unconfirmed order.
        Returns ("filled", result) | ("missing", None) | ("unknown", None).
        result is the same as buy() or sell() would have returned."""
        try:
            o = self.c.get_order(self.cfg.symbol, client_id=cid)
        except AsterError as e:
            if e.code == -2013 or "not exist" in str(e.msg).lower():
                return "missing", None
            return "unknown", None
        except requests.RequestException:
            return "unknown", None
        q, quote, fb, fq = self._fill(o)
        if not q:
            return "missing", None
        if side == "BUY":
            fb = fb or q * self.fee
            return "filled", (q - fb, quote + fq, quote / q)
        fq = fq or quote * self.fee
        return "filled", (quote - fq, quote / q, q)

    def _fill(self, o):
        if o.get("status") not in ("FILLED", "PARTIALLY_FILLED") or float(o.get("executedQty", 0)) == 0:
            time.sleep(0.5)
            o = {**o, **self.c.get_order(self.cfg.symbol, order_id=o["orderId"])}
        qty = float(o.get("executedQty", 0))
        quote = float(o.get("cummulativeQuoteQty") or o.get("cumQuote") or 0)
        fee_base = fee_quote = 0.0
        for f in o.get("fills", []) or []:
            if f.get("commissionAsset") == self.cfg.base_asset:
                fee_base += float(f.get("commission", 0))
            elif f.get("commissionAsset") == self.cfg.quote_asset:
                fee_quote += float(f.get("commission", 0))
        return qty, quote, fee_base, fee_quote

    def _fill_fees(self, o):
        q, quote, fb, fq = self._fill(o)
        if q and not o.get("fills"):        # fill details unavailable (recovered order): estimate the fee
            if o.get("side", "BUY") == "BUY":
                fb = q * self.fee
            else:
                fq = quote * self.fee
        return q, quote, fb, fq

    def _execute(self, side, want_qty):
        """Market order for want_qty. Aster's spot book is thin, so an order can fill only partly
        (the rest is cancelled at Aster's price limit). Then send follow-up orders for the remainder
        at fresh prices, up to TOPUP_TRIES times, and return the combined fill."""
        got_q = got_quote = fee_b = fee_q = 0.0
        orders, remaining = 0, want_qty
        while remaining >= self.step and orders <= self.TOPUP_TRIES:
            if orders:
                time.sleep(2)
                self.quote()
                px = self.ask if side == "BUY" else self.bid
                if remaining * px < self.min_notional:
                    break                  # remainder too small for Aster's minimum order
            try:
                o = self._place(side, remaining)
            except OrderStateUnknown:
                if orders == 0:
                    raise                  # nothing filled yet: let the engine pause and resolve it
                self.note_extra = "a follow-up order could not be confirmed"
                break
            except Exception:
                if orders == 0:
                    raise
                break
            o.setdefault("side", side)
            q, quote, fb, fq = self._fill_fees(o)
            orders += 1
            if q <= 0:
                break                      # nobody on the other side right now
            got_q += q; got_quote += quote; fee_b += fb; fee_q += fq
            remaining = self.c.floor_qty(want_qty - got_q)
        if got_q <= 0:
            raise RuntimeError(f"{side} not filled: no {'sellers' if side == 'BUY' else 'buyers'} on Aster "
                               f"within the price limit right now")
        px_now = (got_quote / got_q) if got_q else 0
        if (want_qty - got_q) * px_now >= self.min_notional:      # a meaningful part is missing
            self.note = (f"{side} only partly filled: {got_q:.4f} of {want_qty:.4f} BNB after {orders} "
                         f"order{'s' if orders > 1 else ''} (Aster's order book was thin)")
        elif orders > 1:
            self.note = f"{side} filled in {orders} parts (Aster's order book was thin)"
        return got_q, got_quote, fee_b, fee_q

    def buy(self, usdt):
        self.note = self.note_extra = None
        p = self.ask
        qty = self.c.floor_qty(usdt / p)
        q, quote, fb, fq = self._execute("BUY", qty)
        return q - fb, quote + fq, quote / q

    def sell(self, qty):
        self.note = self.note_extra = None
        # never try to sell more BNB than the wallet really holds
        free = self.c.balances().get(self.cfg.base_asset, 0.0)
        qty = self.c.floor_qty(min(qty, free))
        if qty <= 0:
            raise RuntimeError(f"no {self.cfg.base_asset} available in the Aster wallet to sell")
        q, quote, fb, fq = self._execute("SELL", qty)
        return quote - fq, quote / q, q

    def deposit(self, amount):
        raise RuntimeError("Deposit real USDT from SafePal to your Aster spot wallet")
