"""
The Wave engine - your rules exactly:

  START        Buy immediately with the start amount (if the wallet has the USDT).
  PRICE UP     Every open buy ("hook") has its own sell target = the price where selling gives the
               chosen NET profit after both fees. When reached: SELL that hook, then BUY again right away.
  PRICE DOWN   Every time price falls another margin % below the last buy level: BUY again.
  WALLET       Every buy opportunity checks the USDT balance first. No funds -> skip and wait for the
               next opportunity (the reference still steps down, so the next check is another margin % lower).
  COMPOUNDING  Each net profit is added to the buy size, so every following buy is bigger.
  NO STOP-LOSS Hooks are never sold at a loss; they wait for their target however long it takes.
"""
import csv
import json
import logging
import os
import threading
import time
import uuid
from collections import deque
from datetime import datetime, timedelta, timezone

from .config import MARGINS
from .exchange import OrderStateUnknown

log = logging.getLogger("wave")
MANILA = timezone(timedelta(hours=8))
RUNNING, NO_NEW_BUYS, STOPPED = "RUNNING", "NO_NEW_BUYS", "STOPPED"


def _now():
    return time.time()


class WaveEngine:
    def __init__(self, cfg, exchange_factory, data_dir=None, market=None, name=""):
        self.cfg = cfg
        self.mk = market                          # shared price feed and candles (wave/market.py)
        self.name = name                          # whose bot this is (for the server log)
        self.lock = threading.RLock()
        self.data_dir = data_dir or cfg.data_dir
        os.makedirs(self.data_dir, exist_ok=True)
        self.state_path = os.path.join(self.data_dir, "wave_state.json")
        self.waves_path = os.path.join(self.data_dir, "waves.csv")
        self.events_path = os.path.join(self.data_dir, "events.log")
        self.s = self._load()
        self.ex = exchange_factory(self.s)
        self.events = deque(self._tail_events(), maxlen=300)
        self.waves = self._load_waves()
        self.market = None
        self._last_market = 0
        self.price = self.bid = self.ask = None
        self.price_ok = False
        self.last_error = None
        self.balances = {}
        self._last_sample = 0
        self._last_bal = 0
        self._last_nofunds_log = 0
        self._last_save = 0
        self._number_buys()

    # ================================================================ persistence
    def _load(self):
        try:
            with open(self.state_path) as f:
                s = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            s = {}
        s.setdefault("status", STOPPED)
        s.setdefault("margin", 1.0)
        s.setdefault("base_amount", 20.0)
        s.setdefault("buy_size", s["base_amount"])
        s.setdefault("reference", None)
        s.setdefault("lots", [])
        s.setdefault("realized", 0.0)
        s.setdefault("dust_qty", 0.0)
        s.setdefault("dust_cost", 0.0)
        s.setdefault("started_at", None)
        s.setdefault("skipped_no_funds", 0)
        s.setdefault("pending", None)
        return s

    def save(self):
        tmp = self.state_path + ".tmp"
        with open(tmp, "w") as f:
            json.dump(self.s, f, indent=1)
        os.replace(tmp, self.state_path)
        self._last_save = _now()

    def _tail_events(self):
        try:
            with open(self.events_path) as f:
                lines = f.readlines()[-300:]
            out = []
            for l in lines:
                t, _, m = l.rstrip("\n").partition(" | ")
                out.append({"t": float(t) if t.replace(".", "").isdigit() else 0, "msg": m, "kind": "info"})
            return out
        except FileNotFoundError:
            return []

    def _load_waves(self):
        try:
            with open(self.waves_path, newline="") as f:
                rows = list(csv.DictReader(f))
            for r in rows:
                for k in ("t_buy", "t_sell", "buy_price", "sell_price", "spent", "received", "profit", "qty", "margin"):
                    r[k] = float(r[k])
                if r.get("no"):
                    r["no"] = int(float(r["no"]))
            return rows[-2000:]
        except FileNotFoundError:
            return []

    def _record_wave(self, w):
        self.waves.append(w)
        header = None
        if os.path.exists(self.waves_path):
            with open(self.waves_path, newline="") as f:
                header = next(csv.reader(f), None)
        if header is not None and set(w) - set(header):
            self._rewrite_waves()                 # new column (e.g. buy number): rewrite with a wider header
            return
        with open(self.waves_path, "a", newline="") as f:
            wr = csv.DictWriter(f, fieldnames=header or list(w.keys()), restval="", extrasaction="ignore")
            if header is None:
                wr.writeheader()
            wr.writerow(w)

    def event(self, msg, kind="info"):
        e = {"t": _now(), "msg": msg, "kind": kind}
        self.events.append(e)
        log.info("[%s] %s", self.name, msg) if self.name else log.info(msg)
        with open(self.events_path, "a") as f:
            f.write(f"{e['t']:.0f} | {msg}\n")

    # ================================================================ helpers
    @property
    def m(self):
        return self.s["margin"] / 100.0

    def target_for(self, spent, qty):
        """Sell price that returns spent x (1 + net margin) after the sell fee (per-unit cost basis,
        so exchange rounding never changes your margin; rounding crumbs are carried to the next sell)."""
        return spent * (1 + self.m) / (qty * (1 - self.ex.fee))

    def required_rise(self, margin_pct):
        """Price rise needed for a given net margin, including buy + sell fees."""
        f = self.ex.fee
        return ((1 + margin_pct / 100) / ((1 - f) ** 2) - 1) * 100

    def refresh_balances(self, force=False):
        if force or _now() - self._last_bal > (30 if self.ex.is_live else 5):
            self.balances = self.ex.balances()
            self._last_bal = _now()
        return self.balances

    # ================================================================ trading actions
    def try_buy(self, reason):
        if reason == "waiting":
            if _now() - getattr(self, "_last_wait", 0) < 10:
                return False
            self._last_wait = _now()
        size = round(self.s["buy_size"], 2)
        if size < self.ex.min_notional:
            self.event(f"Buy size {size:.2f} USDT is below Aster's minimum order ({self.ex.min_notional:.2f}).", "warn")
            return False
        bal = self.refresh_balances(force=True).get(self.cfg.quote_asset, 0.0)
        if bal + 1e-9 < size:
            self.s["skipped_no_funds"] += 1
            if _now() - self._last_nofunds_log > 60 or reason != "waiting":
                self.event(f"Buy chance ({reason}) skipped: wallet has {bal:.2f} USDT, needs {size:.2f}. Waiting for funds.", "warn")
                self._last_nofunds_log = _now()
            return False
        try:
            self.ex.quote()                      # fresh best ask right before buying
            qty, spent, px = self.ex.buy(size)
        except OrderStateUnknown as e:
            self._safety_pause(e, {"reason": reason})
            return False
        except Exception as e:
            self.event(f"BUY failed: {e}", "error")
            return False
        self._add_lot(qty, spent, px, reason)
        self._log_note()
        return True

    def _log_note(self):
        note = getattr(self.ex, "note", None)
        extra = getattr(self.ex, "note_extra", None)
        if note or extra:
            self.event("Note: " + "; ".join(x for x in (note, extra) if x) + ".", "warn")
            self.ex.note = self.ex.note_extra = None

    def _add_lot(self, qty, spent, px, reason):
        target = self.target_for(spent, qty)
        self.s["buy_seq"] = self.s.get("buy_seq", 0) + 1
        lot = {"id": uuid.uuid4().hex[:8], "no": self.s["buy_seq"], "t": _now(), "price": px, "spent": spent, "qty": qty,
               "target": target, "margin": self.s["margin"], "reason": reason}
        self.s["lots"].append(lot)
        self.s["reference"] = px
        self.refresh_balances(force=True)
        self.event(f"BUY {qty:.4f} {self.cfg.base_asset} @ {px:,.2f} for {spent:.2f} USDT ({reason}). "
                   f"Sell target {target:,.2f}.", "buy")
        self.save()

    def sell_lot(self, lot, reason="target reached"):
        # add the carried rounding crumbs (with their cost) so nothing is lost to exchange step sizes
        total_q = lot["qty"] + self.s["dust_qty"]
        total_c = lot["spent"] + self.s["dust_cost"]
        sell_q = self.ex.floor_qty(total_q)
        if sell_q <= 0:
            return False
        try:
            self.ex.quote()                      # fresh best bid right before selling
            received, px, sold = self.ex.sell(sell_q)
        except OrderStateUnknown as e:
            self._safety_pause(e, {"lot_id": lot["id"], "reason": reason})
            return False
        except Exception as e:
            self.event(f"SELL failed: {e}", "error")
            return False
        self._finish_sell(lot, received, px, sold, reason)
        self._log_note()
        return True

    def _finish_sell(self, lot, received, px, sold, reason):
        total_q = lot["qty"] + self.s["dust_qty"]
        total_c = lot["spent"] + self.s["dust_cost"]
        sell_q = min(sold, total_q) if sold else self.ex.floor_qty(total_q)
        left_q = total_q - sell_q
        if left_q >= self.ex.step * 1.5:
            # only part sold: keep the rest open as this buy, with its ORIGINAL target (never sold below it)
            cost = total_c * sell_q / total_q
            profit = received - cost
            lot["qty"], lot["spent"] = left_q, total_c - cost
            self.s["dust_qty"] = self.s["dust_cost"] = 0.0
            self.s["realized"] += profit
            self.s["buy_size"] = max(self.ex.min_notional, self.s["buy_size"] + profit)
            self._record_wave({"no": lot.get("no", ""), "t_buy": lot["t"], "t_sell": _now(), "buy_price": lot["price"], "sell_price": px,
                               "qty": sell_q, "spent": cost, "received": received,
                               "profit": profit, "margin": lot["margin"], "reason": reason + " (part)"})
            self.refresh_balances(force=True)
            self.event(f"SELL (part) {sell_q:.4f} {self.cfg.base_asset} @ {px:,.2f} -> {received:.2f} USDT, "
                       f"net profit {profit:+.4f}. The remaining {left_q:.4f} {self.cfg.base_asset} stays open "
                       f"with its target {lot['target']:,.2f}.", "sell")
            self.save()
            return
        cost = total_c * sell_q / total_q
        self.s["dust_qty"], self.s["dust_cost"] = total_q - sell_q, total_c - cost
        profit = received - cost
        self.s["lots"].remove(lot)
        self.s["realized"] += profit
        old = self.s["buy_size"]
        self.s["buy_size"] = max(self.ex.min_notional, old + profit)      # compounding
        self._record_wave({"no": lot.get("no", ""), "t_buy": lot["t"], "t_sell": _now(), "buy_price": lot["price"], "sell_price": px,
                           "qty": sell_q, "spent": cost, "received": received,
                           "profit": profit, "margin": lot["margin"], "reason": reason})
        self.refresh_balances(force=True)
        self.event(f"SELL {sell_q:.4f} {self.cfg.base_asset} @ {px:,.2f} -> {received:.2f} USDT. "
                   f"Net profit {profit:+.4f} USDT. Next buy size {self.s['buy_size']:.2f}.", "sell")
        self.save()

    def _safety_pause(self, err, context):
        """An order's outcome is unknown: stop trading instead of guessing, keep asking Aster about it."""
        prev = self.s["status"] if self.s["status"] != STOPPED else RUNNING
        self.s["pending"] = {"cid": err.cid, "side": err.side, "prev_status": prev, "since": _now(), **context}
        self.s["status"] = STOPPED
        self.event(f"PAUSED FOR SAFETY: a {err.side} order was sent but Aster didn't confirm it. "
                   f"The bot keeps checking with Aster and resumes by itself once it knows the result.", "error")
        self.save()

    def _resolve_pending(self):
        """Re-check an unconfirmed order every 20 s; record it (or confirm it never happened), then resume."""
        pend = self.s.get("pending")
        if not pend or _now() - getattr(self, "_last_pending_check", 0) < 20:
            return
        self._last_pending_check = _now()
        state, result = self.ex.check_order(pend["cid"], pend["side"])
        if state == "unknown":
            if _now() - pend["since"] > 3600 and not pend.get("warned"):
                pend["warned"] = True
                self.event("Still can't reach Aster to confirm the last order (over 1 hour). "
                           "Please check your Aster spot wallet.", "error")
            return
        if state == "filled":
            if pend["side"] == "BUY":
                qty, spent, px = result
                self._add_lot(qty, spent, px, pend.get("reason", "recovered"))
                self.event("Recovered: the unconfirmed BUY did go through and is now tracked with its sell target.", "info")
            else:
                lot = next((l for l in self.s["lots"] if l["id"] == pend.get("lot_id")), None)
                if lot:
                    received, px, sold = result
                    self._finish_sell(lot, received, px, sold, pend.get("reason", "target reached"))
                self.event("Recovered: the unconfirmed SELL did go through and is recorded.", "info")
        else:
            self.event(f"Confirmed: the unconfirmed {pend['side']} was never placed. Nothing changed.", "info")
        self.s["pending"] = None
        if self.s["status"] == STOPPED:
            self.s["status"] = pend["prev_status"]
            self.event("Resumed automatically.", "info")
        self.save()

    # ================================================================ main loop
    def tick(self):
        with self.lock:
            try:
                bid, ask = self.mk.quote()
                p = (bid + ask) / 2
                self.price, self.bid, self.ask, self.price_ok = p, bid, ask, True
            except Exception as e:
                self.price_ok = False
                self.last_error = f"Price feed: {e}"
                return
            now = _now()
            self.market = self.mk.market
            try:
                self.refresh_balances()
            except Exception as e:
                self.last_error = f"Wallet: {e}"

            if self.s.get("pending"):
                self._resolve_pending()
            st = self.s["status"]
            if st == STOPPED:
                return

            # 1) waves up: sell every hook whose target is reached, then re-hook immediately
            for lot in sorted(self.s["lots"], key=lambda l: l["target"]):
                if self.s["status"] == STOPPED:              # paused for safety mid-cycle
                    break
                if bid >= lot["target"]:                       # a sell would really get this price
                    if self.sell_lot(lot) and self.s["status"] == RUNNING:
                        self.try_buy("re-hook after sell")

            if self.s["status"] == RUNNING:
                ref = self.s["reference"]
                if not self.s["lots"] and ref is None:
                    self.try_buy("waiting")
                elif ref is not None and ask <= ref * (1 - self.m):   # a buy would really pay this price
                    # 2) wave down: another margin % lower -> buy chance
                    if not self.try_buy(f"price -{self.s['margin']}%"):
                        self.s["reference"] = ref * (1 - self.m)      # step the line down; check again lower
                        self.save()
                elif not self.s["lots"] and ref is not None and ask > ref:
                    # nothing open and price above the last level: hang a new hook when funds allow
                    self.try_buy("waiting")

            if self.s["status"] == NO_NEW_BUYS and not self.s["lots"]:
                self.s["status"] = STOPPED
                self.event("All hooks sold. Bot stopped.", "info")
                self.save()

            self.last_error = None
            if now - self._last_save > 15:
                self.save()

    # ================================================================ controls (from the web page)
    def start(self, margin, amount):
        with self.lock:
            if self.s["status"] != STOPPED:
                raise ValueError("Bot is already running")
            if margin not in MARGINS:
                raise ValueError("Choose a profit margin from the list")
            if amount < self.ex.min_notional:
                raise ValueError(f"Amount must be at least {self.ex.min_notional:.2f} USDT (Aster minimum order)")
            bal = self.refresh_balances(force=True).get(self.cfg.quote_asset, 0.0)
            if bal + 1e-9 < amount:
                raise ValueError(f"Not enough USDT in the wallet: {bal:.2f} available, {amount:.2f} needed")
            self.s.update(status=RUNNING, margin=margin, base_amount=amount, buy_size=amount,
                          started_at=_now(), reference=None)
            self.event(f"START: net profit {margin}% per hook, start amount {amount:.2f} USDT.", "info")
            self.try_buy("start")
            self.save()

    def update_settings(self, margin, amount):
        """Change profit per hook and buy amount while running. Open buys keep their own targets;
        new buys (and the next buy-lower step) use the new values. Compounding continues from the new amount."""
        with self.lock:
            if margin not in MARGINS:
                raise ValueError("Choose a profit margin from the list")
            if amount < self.ex.min_notional:
                raise ValueError(f"Amount must be at least {self.ex.min_notional:.2f} USDT (Aster minimum order)")
            old_m, old_a = self.s["margin"], self.s["buy_size"]
            self.s.update(margin=margin, base_amount=amount, buy_size=amount)
            changes = []
            if margin != old_m:
                changes.append(f"profit per hook {old_m}% -> {margin}%")
            if abs(amount - old_a) > 1e-9:
                changes.append(f"buy amount {old_a:.2f} -> {amount:.2f} USDT")
            self.event("Settings changed: " + (", ".join(changes) or "no change") +
                       ". Open buys keep their targets; new buys use the new settings.", "info")
            self.save()

    def stop(self, how):
        with self.lock:
            if how == "no_new_buys":
                if self.s["status"] == RUNNING:
                    self.s["status"] = NO_NEW_BUYS if self.s["lots"] else STOPPED
                    self.event("No new buys: open hooks will still sell at their targets.", "info")
            elif how == "stop":
                self.s["status"] = STOPPED
                self.event(f"STOPPED. {len(self.s['lots'])} open hooks kept (they will sell when you start again).", "info")
            elif how == "sell_all":
                self.s["status"] = STOPPED
                for lot in list(self.s["lots"]):
                    self.sell_lot(lot, "sold by you")
                self.event("SELL ALL done. Bot stopped.", "info")
            elif how == "resume":
                if self.s["status"] != RUNNING:
                    self.s["status"] = RUNNING
                    self.event("Resumed.", "info")
            self.save()

    def paper_deposit(self, amount):
        with self.lock:
            self.ex.deposit(amount)
            self.refresh_balances(force=True)
            self.event(f"Test funds added: +{amount:.2f} USDT (paper wallet).", "info")
            self.save()

    # ---------------------------------------------------------------- candles (shared by all bots)
    def candles_since(self, since):
        return self.mk.candles_since(since)

    def long_candles(self, tf):
        return self.mk.long_candles(tf)

    # ---------------------------------------------------------------- buy numbering
    def _number_buys(self):
        """Every buy gets a running number (#1, #2, ...) from the very first buy. Older data without
        numbers is numbered once, in time order (each completed buy counted once)."""
        if "buy_seq" in self.s and all("no" in l for l in self.s["lots"]):
            return
        times = sorted({round(float(w["t_buy"]), 3) for w in self.waves} | {round(l["t"], 3) for l in self.s["lots"]})
        number = {t: i + 1 for i, t in enumerate(times)}
        for l in self.s["lots"]:
            l["no"] = number[round(l["t"], 3)]
        for w in self.waves:
            w["no"] = number.get(round(float(w["t_buy"]), 3), "")
        self.s["buy_seq"] = len(times)
        self._rewrite_waves()
        self.save()

    def _rewrite_waves(self):
        if not self.waves:
            return
        fields = []
        for w in self.waves:
            for k in w:
                if k not in fields:
                    fields.append(k)
        tmp = self.waves_path + ".tmp"
        with open(tmp, "w", newline="") as f:
            wr = csv.DictWriter(f, fieldnames=fields, restval="")
            wr.writeheader()
            wr.writerows(self.waves)
        os.replace(tmp, self.waves_path)

    # ================================================================ snapshot for the web page
    def snapshot(self):
        with self.lock:
            p = self.price or 0.0
            lots = []
            for l in sorted(self.s["lots"], key=lambda x: x["price"]):
                bid = self.bid or p
                value = l["qty"] * bid * (1 - self.ex.fee)
                at_target = l["qty"] * l["target"] * (1 - self.ex.fee) - l["spent"]
                lots.append({**l, "value": value, "upnl": value - l["spent"], "target_profit": at_target,
                             "to_target_pct": (l["target"] / bid - 1) * 100 if bid else None})
            today0 = datetime.now(MANILA).replace(hour=0, minute=0, second=0, microsecond=0).timestamp()
            waves = list(self.waves)
            bal = self.balances
            base_val = bal.get(self.cfg.base_asset, 0.0) * p
            ref = self.s["reference"]
            return {
                "mode": "live" if self.ex.is_live else "paper",
                "demo_feed": self.cfg.price_feed == "demo",
                "symbol": self.cfg.symbol, "base": self.cfg.base_asset, "quote": self.cfg.quote_asset,
                "price": self.price, "bid": self.bid, "ask": self.ask, "price_ok": self.price_ok, "error": self.last_error,
                "fee": self.ex.fee, "min_notional": self.ex.min_notional,
                "margins": [{"m": m, "rise": self.required_rise(m)} for m in MARGINS],
                "status": self.s["status"], "margin": self.s["margin"],
                "base_amount": self.s["base_amount"], "buy_size": self.s["buy_size"],
                "next_buy_price": ref * (1 - self.m) if ref and self.s["status"] == RUNNING else None,
                "reference": ref, "started_at": self.s["started_at"],
                "balances": {"quote": bal.get(self.cfg.quote_asset, 0.0), "base": bal.get(self.cfg.base_asset, 0.0),
                             "base_value": base_val, "total": bal.get(self.cfg.quote_asset, 0.0) + base_val},
                "lots": lots,
                "invested": sum(l["spent"] for l in lots),
                "upnl": sum(l["upnl"] for l in lots),
                "target_profit": sum(l["target_profit"] for l in lots),
                "realized": sum(w["profit"] for w in waves),
                "today": sum(w["profit"] for w in waves if w["t_sell"] >= today0),
                "waves_total": len(waves), "waves_today": sum(1 for w in waves if w["t_sell"] >= today0),
                "skipped": self.s["skipped_no_funds"],
                "waves": waves[-300:][::-1],
                "events": list(self.events)[-120:][::-1],
                "market": self.market, "now": _now(),
                "buy_seq": self.s.get("buy_seq", 0),
            }
