"""MVX API example (Python 3.10+, standard library only).

Set MVX_BASE_URL and MVX_API_SECRET locally. Never put an API secret in source code.
This example only reads the market and wallet when run.
"""
import json
import os
import urllib.error
import urllib.parse
import urllib.request
import uuid


class NoRedirects(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, request, fp, code, message, headers, new_url):
        raise urllib.error.HTTPError(request.full_url, code, "API redirects are disabled", headers, fp)


class MVX:
    def __init__(self, base_url, api_secret):
        parsed = urllib.parse.urlparse(base_url)
        local = parsed.hostname in ("localhost", "127.0.0.1", "client.localhost")
        if parsed.scheme != "https" and not (local and parsed.scheme == "http"):
            raise ValueError("Use HTTPS, except for the local development GUI")
        if parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path not in ("", "/"):
            raise ValueError("Use the Client origin, without credentials or query parameters")
        self.base = base_url.rstrip("/")
        self.opener = urllib.request.build_opener(NoRedirects())
        self.token = None
        self.token = self.request("POST", "/api/token", {"APIPassword": api_secret})["Token"]

    def request(self, method, path, body=None, key=None):
        if not path.startswith("/") or path.startswith("//"):
            raise ValueError("A relative API path is required")
        headers = {"Accept": "application/json"}
        if self.token:
            headers["X-API-KEY"] = self.token
        if key:
            headers["Idempotency-Key"] = key
        data = None
        if body is not None:
            headers["Content-Type"] = "application/json"
            data = json.dumps(body).encode("utf-8")
        request = urllib.request.Request(self.base + path, data=data, headers=headers, method=method)
        # No automatic retries: a network failure does not prove that an order failed.
        try:
            with self.opener.open(request, timeout=10) as response:
                return json.load(response)
        except urllib.error.HTTPError as error:
            raise RuntimeError(f"MVX returned HTTP {error.code}; check access, limits and receipts") from None

    def board(self, symbol="SOMY"):
        return self.request("GET", "/api/board/" + urllib.parse.quote(symbol + "@1", safe="@"))

    def cash(self):
        return self.request("GET", "/api/wallet/cash")

    def price_history(self, symbol="SOMY", interval="1m", limit=120, *, from_time=None, to_time=None, before=None):
        """Read OHLCV. Keep response from/to when following its next cursor.

        No-trade intervals are omitted; complete=False bars can still change.
        Week/day boundaries use UTC. No order is sent by this method.
        """
        query = {"symbol": symbol, "interval": interval, "limit": limit}
        for name, value in [("from", from_time), ("to", to_time), ("before", before)]:
            if value is not None:
                query[name] = value
        return self.request("GET", "/mvx/v1/price-history?" + urllib.parse.urlencode(query))

    def place_order(self, symbol, side, quantity, price, idempotency_key):
        """Requires a trade key. Persist key and request BEFORE calling this method."""
        return self.request("POST", "/mvx/v1/orders", {
            "symbol": symbol, "side": side, "qty": quantity, "price": price
        }, key=idempotency_key)

    def order_receipt(self, idempotency_key):
        return self.request("GET", "/mvx/v1/receipts?keys=" + urllib.parse.quote(idempotency_key))

    def close(self):
        if self.token:
            self.request("POST", "/mvx/v1/logout", {})
            self.token = None


def main():
    client = MVX(os.environ.get("MVX_BASE_URL", "http://127.0.0.1:20812"), os.environ["MVX_API_SECRET"])
    try:
        board = client.board()
        print("SOMY price:", board.get("CurrentPrice"))
        print("Cash:", client.cash()["_me"]["CashBalance"])
        # Read-only chart example:
        # history = client.price_history("SOMY", "5m", 120)
        # for candle in history["items"]:
        #     print(candle["at"], candle["open"], candle["high"],
        #           candle["low"], candle["close"], candle["volume"], candle["complete"])
        # Follow history["next"] only when history["more"] is True:
        # older = client.price_history("SOMY", "5m", 120,
        #     from_time=history["from"], to_time=history["to"], before=history["next"])
        # Example only; intentionally not submitted:
        # key = str(uuid.uuid4())
        # Persist key and exact order contents first, then:
        # result = client.place_order("SOMY", "BUY", 100, 1000, key)
        # If the result is uncertain, use client.order_receipt(key).
        # A missing receipt is not proof of failure. Do not create a new key to retry blindly.
    finally:
        client.close()


if __name__ == "__main__":
    main()
