"""
Wave Bot - BNB/USDT spot on Aster. Start it with:  bash run.sh   (or: python app.py)
Then open http://localhost:8090
"""
import json
import logging
import os
import shutil
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

from wave.config import Config
from wave.aster_spot import AsterSpot
from wave.market import Market
from wave.users import Users, KeyBox
from wave.bots import Bots
from wave.auth import Auth

cfg = Config()
os.makedirs(cfg.data_dir, exist_ok=True)
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s",
                    handlers=[logging.StreamHandler(), logging.FileHandler(os.path.join(cfg.data_dir, "bot.log"))])
log = logging.getLogger("app")
HERE = os.path.dirname(os.path.abspath(__file__))
WEB = os.path.join(HERE, "web", "index.html")
LOGIN = os.path.join(HERE, "web", "login.html")
PUBLIC = os.path.join(HERE, "web", "public.html")

# move files from very old versions (single data folder) into data/paper
_old = os.path.join(cfg.data_dir, "wave_state.json")
if os.path.exists(_old) and not os.path.exists(os.path.join(cfg.data_dir, "paper", "wave_state.json")):
    os.makedirs(os.path.join(cfg.data_dir, "paper"), exist_ok=True)
    for f in ("wave_state.json", "waves.csv", "events.log"):
        if os.path.exists(os.path.join(cfg.data_dir, f)):
            shutil.move(os.path.join(cfg.data_dir, f), os.path.join(cfg.data_dir, "paper", f))

users = Users(cfg.data_dir, cfg.username, cfg.password, cfg.max_users)
auth = Auth(cfg.data_dir, users)
box = KeyBox(cfg.data_dir)
market = Market(cfg, AsterSpot(cfg.spot_url, cfg.chain_id, "", "", ""))
bots = Bots(cfg, market, box, users)
SERVER_IP = {"ip": cfg.server_ip}


def _find_server_ip():
    if SERVER_IP["ip"]:
        return
    try:
        import requests
        SERVER_IP["ip"] = requests.get("https://api.ipify.org", timeout=8).text.strip()
    except Exception:
        pass


def public_snapshot():
    """What the open front page may show (the owner's bot): balances, profit, buys, prices.
    No addresses, keys or controls."""
    s = bots.get(users.owner).engine.snapshot()
    b = s["balances"]
    keep_lot = ("no", "t", "price", "spent", "qty", "target", "to_target_pct", "upnl", "target_profit")
    keep_wave = ("no", "t_buy", "t_sell", "buy_price", "sell_price", "spent", "profit")
    return {
        "mode": s["mode"], "status": s["status"], "margin": s["margin"],
        "price": s["price"], "market": s["market"], "bid": s["bid"], "ask": s["ask"], "price_ok": s["price_ok"],
        "capital": b["total"], "usdt": b["quote"], "bnb": b["base"], "bnb_value": b["base_value"],
        "realized": s["realized"], "today": s["today"], "waves_total": s["waves_total"],
        "waves_today": s["waves_today"], "invested": s["invested"], "upnl": s["upnl"],
        "target_profit": s["target_profit"],
        "lots": [{k: l.get(k) for k in keep_lot} for l in s["lots"]],
        "waves": [{k: w.get(k) for k in keep_wave} for w in s["waves"][:50]],
        "next_buy_price": s["next_buy_price"], "now": s["now"],
    }


def short(a):
    return a[:6] + "…" + a[-4:] if a else ""


def account_info(bot, can_edit):
    c, w = bot.creds, bot.wallet
    res = w.result if w else None
    return {
        "connected_address": bool(c.user), "connected_api": c.has_api,
        "user": c.user, "user_short": short(c.user), "signer_short": short(c.signer),
        "can_edit": can_edit, "server_ip": SERVER_IP["ip"],
        "safepal": res, "safepal_error": (w.error if w and not res else None),
        "aster": bot.aster_balances(), "aster_error": bot.aster_error,
    }


class Handler(BaseHTTPRequestHandler):
    def log_message(self, *a):
        pass

    @property
    def proxied(self):
        """True when the request came through the HTTPS web server (Caddy) rather than directly."""
        return self.client_address[0] in ("127.0.0.1", "::1") and bool(self.headers.get("X-Forwarded-For"))

    @property
    def local(self):
        # only the computer running the bot (or an SSH tunnel to it) counts as local - never visitors via HTTPS
        return self.client_address[0] in ("127.0.0.1", "::1") and not self.proxied

    @property
    def visitor_ip(self):
        if self.proxied:
            return self.headers.get("X-Forwarded-For").split(",")[0].strip()
        return self.client_address[0]

    @property
    def https(self):
        return self.headers.get("X-Forwarded-Proto", "") == "https"

    @property
    def user(self):
        return auth.check(self.headers.get("Cookie"))

    def _send(self, code, body, ctype="application/json", headers=None):
        if isinstance(body, (dict, list)):
            body = json.dumps(body, default=str)
        b = body.encode() if isinstance(body, str) else body
        self.send_response(code)
        self.send_header("Content-Type", ctype)
        self.send_header("Cache-Control", "no-store")
        self.send_header("Content-Length", str(len(b)))
        self.send_header("X-Frame-Options", "DENY")
        self.send_header("Referrer-Policy", "no-referrer")
        for k, v in (headers or {}).items():
            self.send_header(k, v)
        self.end_headers()
        self.wfile.write(b)

    def _redirect(self, to):
        self.send_response(302)
        self.send_header("Location", to)
        self.send_header("Cache-Control", "no-store")
        self.end_headers()

    def do_GET(self):
        path = self.path.split("?")[0]
        if path == "/login":
            if self.user:
                return self._redirect("/dashboard")
            with open(LOGIN, "rb") as f:
                return self._send(200, f.read(), "text/html; charset=utf-8")
        if path == "/chart.js":
            with open(os.path.join(HERE, "web", "chart.js"), "rb") as f:
                return self._send(200, f.read(), "application/javascript; charset=utf-8")
        # ---- open front page (balance, profit, buys, chart) ----
        if path in ("/", "/index.html"):
            if not cfg.public_view:
                return self._redirect("/dashboard" if self.user else "/login")
            with open(PUBLIC, "rb") as f:
                return self._send(200, f.read(), "text/html; charset=utf-8")
        if path == "/api/auth_info":
            return self._send(200, {"signup": cfg.signup, "public_view": cfg.public_view})
        if path == "/api/candles":
            # chart candles (same for everyone): open to the front page (when it's on) and to signed-in users
            if not (cfg.public_view or self.user):
                return self._send(401, {"error": "Please sign in", "login": True})
            from urllib.parse import urlparse, parse_qs
            q = parse_qs(urlparse(self.path).query)
            tf = q.get("tf", [""])[0]
            if tf:
                return self._send(200, market.long_candles(tf))
            since = int(float(q.get("since", ["0"])[0]))
            return self._send(200, market.candles_since(since))
        if path == "/api/public":
            if not cfg.public_view:
                return self._send(404, {"error": "not found"})
            return self._send(200, {**public_snapshot(), "signed_in": bool(self.user)})
        # ---- everything below needs a signed-in session ----
        if not self.user:
            if path.startswith("/api/"):
                return self._send(401, {"error": "Please sign in", "login": True})
            return self._redirect("/login")
        if path == "/dashboard":
            with open(WEB, "rb") as f:
                return self._send(200, f.read(), "text/html; charset=utf-8")
        me = self.user
        if self.path.startswith("/api/state"):
            bot = bots.get(me)
            snap = bot.engine.snapshot()
            snap["account"] = account_info(bot, self.local or self.https)
            snap["signed_in_as"] = me
            snap["is_owner"] = users.is_owner(me)
            return self._send(200, snap)
        if path == "/api/users":
            if not users.is_owner(me):
                return self._send(403, {"error": "Only the owner can see the user list"})
            return self._send(200, bots.summary())
        self._send(404, {"error": "not found"})

    def do_POST(self):
        if self.headers.get("X-Wave-Bot") != "1":
            return self._send(403, {"error": "forbidden"})
        try:
            n = int(self.headers.get("Content-Length", 0))
            d = json.loads(self.rfile.read(n) or b"{}")
        except ValueError:
            return self._send(400, {"error": "bad request"})
        p = self.path
        if p == "/api/login":
            try:
                token = auth.login(self.visitor_ip, d.get("username", ""), d.get("password", ""))
            except ValueError as e:
                return self._send(401, {"error": str(e)})
            log.info("%s signed in from %s", (d.get("username") or "").strip().lower(), self.visitor_ip)
            return self._send(200, {"ok": True}, headers={"Set-Cookie": auth.cookie(token, secure=self.https)})
        if p == "/api/signup":
            if not cfg.signup:
                return self._send(403, {"error": "Sign-up is closed. Ask the owner of this bot for an account."})
            if d.get("password") != d.get("password2"):
                return self._send(400, {"error": "The two passwords don't match"})
            try:
                name, token = auth.signup(self.visitor_ip, d.get("username", ""), d.get("password", ""))
            except ValueError as e:
                return self._send(400, {"error": str(e)})
            bots.get(name)
            log.info("new account %s from %s", name, self.visitor_ip)
            return self._send(200, {"ok": True}, headers={"Set-Cookie": auth.cookie(token, secure=self.https)})
        if p == "/api/logout":
            auth.logout(self.headers.get("Cookie"))
            return self._send(200, {"ok": True}, headers={"Set-Cookie": auth.cookie("", 0, secure=self.https)})
        me = self.user
        if not me:
            return self._send(401, {"error": "Please sign in", "login": True})
        bot = bots.get(me)
        try:
            if p == "/api/start":
                bot.engine.start(float(d["margin"]), float(d["amount"]))
            elif p == "/api/stop":
                bot.engine.stop(d.get("how", "stop"))
            elif p == "/api/settings":
                bot.engine.update_settings(float(d["margin"]), float(d["amount"]))
            elif p == "/api/paper/deposit":
                if bot.mode != "paper":
                    raise ValueError("Test funds are only for paper mode")
                bot.engine.paper_deposit(float(d.get("amount", 100)))
            elif p == "/api/mode":
                bot.switch(d.get("mode"))
            elif p in ("/api/connect", "/api/connect_address", "/api/disconnect"):
                # keys travel only over an encrypted connection (https), or on the computer running the bot
                if not (self.local or self.https):
                    raise ValueError("For safety, open the bot through its https:// address to connect a wallet")
                if p == "/api/disconnect":
                    bot.disconnect()
                elif p == "/api/connect_address":
                    bot.connect_address(d.get("user", ""))
                else:
                    bot.connect_api(d.get("user", ""), d.get("signer", ""), d.get("key", ""))
            elif p == "/api/password":
                if d.get("new") != d.get("new2"):
                    raise ValueError("The two new passwords don't match")
                users.set_password(me, d.get("old", ""), d.get("new", ""))
            elif p == "/api/users/disable":
                if not users.is_owner(me):
                    raise ValueError("Only the owner can do this")
                bots.set_disabled(d.get("name", ""), bool(d.get("disabled")))
            else:
                return self._send(404, {"error": "not found"})
            return self._send(200, {"ok": True})
        except (ValueError, KeyError, RuntimeError) as e:
            return self._send(400, {"error": str(e)})
        except Exception as e:
            log.exception("request")
            return self._send(500, {"error": str(e)})


def start_background():
    market.start()
    bots.start_all()
    threading.Thread(target=_find_server_ip, daemon=True).start()


if __name__ == "__main__":
    start_background()
    print(f"\n  Wave Bot running for {len(users.names())} account(s).  Open  http://localhost:{cfg.port}  in your browser.\n"
          f"  Press Ctrl+C here to stop the program.\n")
    try:
        ThreadingHTTPServer((cfg.host, cfg.port), Handler).serve_forever()
    except KeyboardInterrupt:
        for b in list(bots.b.values()):
            b.engine.save()
        print("Stopped. Settings and open hooks are saved.")
