"""Slay Predict from Python.  Needs: pip install requests

    import slay
    slay.key = "spk_..."            # or set the SLAY_API_KEY environment variable

    slay.quote("btc 5m", "up", 10)  # where it would go (hyperliquid / polymarket) and what it gets
    slay.buy("btc 5m", "up", 10)    # $10 on Up, on whichever venue pays more
    slay.sell("btc 5m", "up")       # sell all of it (or shares=5)
    slay.balance()                  # cash and open positions
    slay.find("lakers")             # markets matching some words
    print(slay.say(slay.buy("btc 5m", "up", 10)))   # one readable line

    slay.paper = True               # practice: $1,000 of fake money on live prices

Orders spend the money in your API wallet (slay.money/api/keys). Every order is safe to retry:
it carries its own id, so a retry never places it twice.
"""
import os
import time
import uuid

import requests

key = os.environ.get("SLAY_API_KEY")
paper = False
API = "https://www.slay.money/api/trade"


class SlayError(Exception):
    """An order Slay refused or couldn't place: .code says why (e.g. insufficient_balance)."""

    def __init__(self, message, code=None, data=None):
        super().__init__(message)
        self.code = code
        self.data = data or {}


def _call(method, path, body=None, params=None):
    if not key:
        raise SlayError("Set slay.key (or SLAY_API_KEY) to your API key from slay.money/api/keys.", "no_key")
    r = requests.request(method, API + path, headers={"authorization": f"Bearer {key}"}, json=body, params=params, timeout=40)
    try:
        data = r.json()
    except ValueError:
        data = {"error": r.text[:200]}
    if r.status_code >= 400:
        raise SlayError(data.get("error", f"HTTP {r.status_code}"), data.get("code"), data)
    return data


def _place(path, body):
    body = {**body, "paper": paper, "externalId": body.get("externalId") or uuid.uuid4().hex}
    try:
        o = _call("POST", path, body)
    except requests.RequestException:
        o = _call("POST", path, body)  # same externalId: never a second order
    # A held order (in-play markets hold orders a few seconds): wait for its answer.
    t = time.time()
    while o.get("status") == "pending" and time.time() - t < 90:
        time.sleep(2)
        o = order(o["id"])
    return o


def buy(market, outcome, usd, max_price=None, venue=None, id=None):
    """Spend `usd` on `outcome` ("up", "yes", "Lakers") of `market` ("btc 5m", an id, or a slay.money link)."""
    return _place("/buy", {"market": market, "outcome": outcome, "usd": usd, "maxPrice": max_price, "venue": venue, "externalId": id})


def quote(market, outcome, usd):
    """What buy() would do, nothing placed: the venue it picks (hyperliquid or polymarket), shares, price, to win."""
    return _call("POST", "/buy", {"market": market, "outcome": outcome, "usd": usd, "paper": paper, "preview": True})


def sell(market, outcome, shares=None, min_price=None, venue=None, id=None):
    """Sell `shares` of `outcome` (all of them when left out)."""
    return _place("/sell", {"market": market, "outcome": outcome, "shares": shares, "minPrice": min_price, "venue": venue, "externalId": id})


def balance():
    """Cash on each venue and open positions (the paper account's with slay.paper = True)."""
    return _call("GET", "/balance", params={"paper": "1"} if paper else None)


def order(id):
    """One order by its id: its status now (filled, partial, unfilled, failed, pending)."""
    return _call("GET", f"/order/{id}")


def find(words):
    """Open markets matching some words, the way buy() and sell() read them."""
    return _call("GET", "/find", params={"q": words})["markets"]


def say(o):
    """One readable line for an answer: say(buy(...)), say(quote(...)), say(balance())."""
    if "cash" in o:
        pos = o.get("positions") or []
        lines = [f"Cash ${o['cash'].get('total') or 0:,.2f}" + (" (practice)" if o.get("paper") else "")]
        lines += [f"  {p.get('shares', 0):g} {p.get('outcome') or ''} - {p.get('title') or p.get('coin')}" for p in pos]
        return "\n".join(lines)
    venue = {"polymarket": "Polymarket", "hyperliquid": "Hyperliquid"}.get(o.get("venue"), o.get("venue"))
    px = f"{(o.get('avgPrice') or 0) * 100:.1f}c"
    tag = " (practice)" if o.get("paper") else ""
    if o.get("status") == "preview":
        return f"Would buy {o.get('shares')} {o.get('outcome')} on {venue} for ${o.get('usd', 0):.2f} at {px}, wins ${o.get('toWin', 0):.2f} - {o.get('market')}"
    if o.get("side") == "sell":
        return f"Sold {o.get('shares')} {o.get('outcome')} on {venue} for ${o.get('usd', 0):.2f} at {px}{tag} - {o.get('status')}"
    return f"Bought {o.get('shares')} {o.get('outcome')} on {venue} for ${o.get('usd', 0):.2f} at {px}, wins ${o.get('toWin', 0):.2f}{tag} - {o.get('status')}"
