"""Bottega SDK for Python agents. Needs eth-account (pip install eth-account).

    from bottega_sdk import BottegaAgent
    agent = BottegaAgent(api="https://bottega.lol/api", private_key=os.environ["AGENT_KEY"])
    skill = agent.load("invoice reader")
    result = skill.run({"text": "..."})   # pays one use from the agent's Bottega balance

The key stays with the agent: permits are signed locally and only the signature is sent.
"""
import json, os, secrets, time, urllib.request, urllib.error, urllib.parse
from eth_account import Account
from eth_account.messages import encode_typed_data
from eth_utils import keccak

USE_FIELDS = [
    {"name": "buyer", "type": "address"}, {"name": "id", "type": "uint256"}, {"name": "uses", "type": "uint32"},
    {"name": "maxPrice", "type": "uint96"}, {"name": "nonce", "type": "uint256"}, {"name": "deadline", "type": "uint64"},
    {"name": "ref", "type": "bytes32"},
]


def canonical(v):
    """JSON with sorted keys and no spaces, matching the server and the JS SDK."""
    if isinstance(v, list):
        return "[" + ",".join(canonical(x) for x in v) + "]"
    if isinstance(v, dict):
        return "{" + ",".join(json.dumps(k, ensure_ascii=False) + ":" + canonical(v[k]) for k in sorted(v)) + "}"
    if isinstance(v, bool) or v is None:
        return json.dumps(v)
    if isinstance(v, float) and v.is_integer():
        return str(int(v))
    return json.dumps(v, ensure_ascii=False)


def input_ref(cid, value):
    return "0x" + keccak(text=f"run:{cid}:{canonical(value)}").hex()


def new_agent_key():
    a = Account.create()
    return {"address": a.address, "private_key": "0x" + a.key.hex().removeprefix("0x")}


class BottegaError(Exception):
    def __init__(self, message, status=None):
        super().__init__(message)
        self.status = status


class Skill:
    def __init__(self, agent, data):
        self._agent, self.data = agent, data
        self.id, self.name, self.price = data["id"], data["name"], int(data["price"])

    def run(self, value):
        """Run once; charged only if the run succeeds."""
        p = self._agent.permit(self.id, value, self.price)
        return self._agent._call("/run", {"id": self.id, "input": value, "permit": p})

    def demo(self):
        return self._agent._call(f"/cartridges/{self.id}/demo")


class BottegaAgent:
    def __init__(self, api, private_key, max_price=None, timeout=90):
        self.api = api.rstrip("/")
        self.account = Account.from_key(private_key)
        self.address = self.account.address
        self.max_price = max_price
        self.timeout = timeout
        self._info = None

    def _call(self, path, body=None):
        data = None if body is None else json.dumps(body).encode()
        req = urllib.request.Request(self.api + path, data=data, headers={"content-type": "application/json"}, method="GET" if body is None else "POST")
        try:
            with urllib.request.urlopen(req, timeout=self.timeout) as r:
                return json.loads(r.read())
        except urllib.error.HTTPError as e:
            try:
                msg = json.loads(e.read()).get("error")
            except Exception:
                msg = None
            raise BottegaError(msg or f"Bottega answered {e.code}.", e.code) from None

    def info(self):
        if self._info is None:
            self._info = self._call("/info")
        return self._info

    def search(self, query="", category=None):
        qs = {"q": query} if query else {}
        if category:
            qs["category"] = category
        return self._call("/cartridges?" + urllib.parse.urlencode(qs))

    def load(self, id_or_name):
        if isinstance(id_or_name, int) or str(id_or_name).isdigit():
            return Skill(self, self._call(f"/cartridges/{id_or_name}"))
        hits = self.search(str(id_or_name))
        if not hits:
            raise BottegaError(f'No tested cartridge matches "{id_or_name}".', 404)
        exact = next((c for c in hits if c["name"].lower() == str(id_or_name).lower()), hits[0])
        return Skill(self, self._call(f"/cartridges/{exact['id']}"))

    def permit(self, cid, value, price):
        i = self.info()
        cap = int(round(float(self.max_price) * 10 ** i["decimals"])) if self.max_price is not None else int(price)
        if int(price) > cap:
            raise BottegaError("This cartridge costs more than this agent's max_price.", 402)
        use = {"buyer": self.address, "id": int(cid), "uses": 1, "maxPrice": cap, "nonce": secrets.randbits(128),
               "deadline": int(time.time()) + 600, "ref": input_ref(cid, value)}
        domain = {"name": "Bottega", "version": "1", "chainId": i["chainId"], "verifyingContract": i["market"]}
        signed = self.account.sign_message(encode_typed_data(domain, {"Use": USE_FIELDS}, use))
        out = {k: (str(v) if k in ("id", "maxPrice", "nonce") else v) for k, v in use.items()}
        return {"use": out, "signature": "0x" + signed.signature.hex().removeprefix("0x")}
