"""A complete paper trading agent for Motion, in one file.

It makes a wallet, reads the market, asks for a quote, opens a long with play SOL, watches it,
and closes it. Signing is done on this machine with solders, the same call a live agent uses.
Nothing here is on chain and no SOL is needed.

    pip install solders
    python "agent example.py"

It talks to the paper trading API at /api/practice/v1, which stays paper trading when the main
address /api/v1 serves the live markets. Set MOTION_API to point it anywhere else.
"""
import base64
import json
import os
import time
import urllib.error
import urllib.request

from solders.keypair import Keypair
from solders.transaction import VersionedTransaction

API = os.environ.get("MOTION_API", "https://motion.trading/api/practice/v1")


def call(path, body=None):
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(API + path, data=data, headers={"Content-Type": "application/json", "User-Agent": "motion paper trading agent"})
    try:
        with urllib.request.urlopen(req, timeout=15) as r:
            return json.loads(r.read())
    except urllib.error.HTTPError as e:
        raise SystemExit("refused: %s" % json.loads(e.read())["error"])


def sign_and_send(wallet, built):
    """Sign each transaction of an order here, then send them in the order given."""
    out = None
    for b64 in built["transactions"]:
        unsigned = VersionedTransaction.from_bytes(base64.b64decode(b64))
        signed = VersionedTransaction(unsigned.message, [wallet])          # the key never leaves this machine
        out = call("/tx/send", {"transaction": base64.b64encode(bytes(signed)).decode()})
    return out


def main():
    wallet = Keypair()                       # any keypair works in paper trading; a fresh one is fine
    me = str(wallet.pubkey())
    print("wallet", me)
    print("mode:", call("/status")["mode"], "| play balance:", call("/wallets/" + me)["balance"], "SOL")

    market = call("/markets/ansem")
    print("Ansem is at", market["price"], "| longs", market["long_size"], "| shorts", market["short_size"])

    quote = call("/quote?market=ansem&side=long&margin=0.5&leverage=5&wallet=" + me)
    if not quote["allowed"]:
        raise SystemExit("not allowed right now: " + quote["reason"])
    print("quote: entry", quote["entry_price"], "| liquidation", quote["liquidation_price"], "| fee", quote["fee"])

    built = call("/tx/open", {"wallet": me, "market": "ansem", "side": "long", "margin": "0.5", "leverage": 5, "slippage_bps": 100})
    sent = sign_and_send(wallet, built)
    print("opened:", sent["result"], "| signature", sent["signature"][:16] + "...")

    entry = float(quote["entry_price"])
    for _ in range(10):                      # watch for a little while; a real agent decides here
        time.sleep(2)
        pos = call("/wallets/%s/positions" % me)["positions"]
        if not pos:
            last = call("/wallets/%s/state" % me)["history"][0]
            if last["kind"] == "band_close":     # closed by the band rule, not liquidated: what it was worth came back
                raise SystemExit("the position was closed by the band rule; %s SOL went back to the wallet" % last["returned"])
            raise SystemExit("the position was liquidated: you lost your margin")
        print("  price %s | profit %s SOL" % (call("/markets/ansem")["price"], pos[0]["profit"]))
        if abs(float(call("/markets/ansem")["price"]) / entry - 1) > 0.02:
            break

    closed = sign_and_send(wallet, call("/tx/close", {"wallet": me, "market": "ansem", "fraction": "1", "slippage_bps": 200}))
    print("closed:", closed["result"])
    print("play balance now:", call("/wallets/" + me)["balance"], "SOL")


if __name__ == "__main__":
    main()
