"""Nod Pass SDK for Python — one file, standard library only (Python 3.9+).

    from nodpass import Nod, Refused

    # in your booking system (system key stk_...)
    nod = Nod(key="stk_...")
    try:
        receipt = nod.authorise_booking(nod_id, agent="atlas", counterparty="courier9",
                                        action="book freight", amount=3950, ref="FX-2291")
        place_the_booking(...)          # only after a receipt
    except Refused as e:
        print("don't book:", e.message)  # e.g. "details differ from what was nodded; a fresh nod is needed"

    # in your agent (agent key atk_...)
    agent = Nod(key="atk_...")
    if agent.passport("courier9")["proof_of_authority"]["owner_verified"]:
        n = agent.ask("courier9", "book freight", 3950, ref="FX-2291", reason="2 containers")
        status = agent.wait_for_nod(n["nod_id"], timeout=600)

    # receiving webhooks
    event = Nod.verify_webhook(secret, raw_body_bytes, request.headers["Nod-Signature"])

Docs: https://nodpass.org/docs
"""
import hashlib, hmac, json, time, urllib.error, urllib.request

__version__ = "1.0.0"
DEFAULT_BASE = "https://api.nodpass.org"


class NodError(Exception):
    """Any non-2xx answer from Nod. `.status` is the HTTP status, `.message` Nod's reason."""

    def __init__(self, status, message):
        super().__init__(f"{status}: {message}")
        self.status, self.message = status, message


class Refused(NodError):
    """Nod's rules refused the action (HTTP 403). Do not proceed."""


class Nod:
    def __init__(self, key=None, base=DEFAULT_BASE, timeout=15):
        self.key, self.base, self.timeout = key, base.rstrip("/"), timeout

    # ---- transport
    def _call(self, method, path, body=None):
        r = urllib.request.Request(self.base + "/v1" + path, method=method,
                                   data=json.dumps(body).encode() if body is not None else None)
        r.add_header("Content-Type", "application/json")
        r.add_header("User-Agent", f"nodpass-python/{__version__}")
        if self.key:
            r.add_header("Authorization", "Bearer " + self.key)
        try:
            with urllib.request.urlopen(r, timeout=self.timeout) as resp:
                return json.loads(resp.read())
        except urllib.error.HTTPError as e:
            try:
                msg = json.loads(e.read()).get("error", e.reason)
            except ValueError:
                msg = e.reason
            raise (Refused if e.code == 403 else NodError)(e.code, msg)

    # ---- anyone
    def passport(self, agent_id):
        """Who the agent acts for, whether its owner is verified, its limits, confirmed jobs, disputes, trust."""
        return self._call("GET", f"/passports/{agent_id}")

    def agent_card(self, agent_id):
        return self._call("GET", f"/agents/{agent_id}/agent-card")

    def verify_message(self, code):
        """Check a signed agent email/call by its short code (e.g. NOD-FBPHYG)."""
        return self._call("GET", f"/verify/{code}")

    # ---- agents (atk_ key)
    def ask(self, counterparty, action, amount, ref, reason="", currency="GBP"):
        """Ask your owner to nod exactly this deal. Returns {nod_id, status: pending|nodded, binding, expires}."""
        return self._call("POST", "/nods", {"counterparty": counterparty, "action": action, "amount": amount,
                                            "currency": currency, "ref": ref, "reason": reason})

    def nod_status(self, nod_id):
        return self._call("GET", f"/nods/{nod_id}")

    def wait_for_nod(self, nod_id, timeout=600, every=5):
        """Poll until the nod is decided (or timeout). Returns the final status dict."""
        end = time.time() + timeout
        while True:
            n = self.nod_status(nod_id)
            if n["status"] != "pending" or time.time() >= end:
                return n
            time.sleep(every)

    def mandate(self, nod_id):
        """Signed, single-use mandate of what was authorised (AP2-style fields) for payment flows."""
        return self._call("GET", f"/nods/{nod_id}/mandate")

    def sign_message(self, to, body, channel="email", subject=""):
        """Sign an email/call/message to a person. Returns header, footer, code and verify URL."""
        return self._call("POST", "/outbound", {"channel": channel, "to": to, "subject": subject, "body": body})

    # ---- company systems (stk_ key)
    def authorise_booking(self, nod_id, agent, counterparty, action, amount, ref, currency="GBP"):
        """Call before placing an agent-made booking. Returns {action_id, receipt}; raises Refused if it doesn't
        exactly match an unused, nodded nod."""
        return self._call("POST", "/actions", {"nod_id": nod_id, "agent": agent, "counterparty": counterparty,
                                               "action": action, "amount": amount, "currency": currency, "ref": ref})

    def report_outcome(self, action_id, type, note=""):
        """type: placed (supplier's system) | delivered | disputed (receiving side)."""
        return self._call("POST", "/outcomes", {"action_id": action_id, "type": type, "note": note})

    def inbox(self):
        return self._call("GET", "/inbox")

    # ---- webhooks
    @staticmethod
    def verify_webhook(secret, body, signature_header, tolerance=300):
        """Check a Nod webhook. `body` = the raw request bytes. Returns the parsed event, or raises ValueError."""
        if isinstance(body, str):
            body = body.encode()
        parts = dict(p.split("=", 1) for p in str(signature_header).split(",") if "=" in p)
        t, v1 = parts.get("t", ""), parts.get("v1", "")
        if not t.isdigit() or abs(time.time() - int(t)) > tolerance:
            raise ValueError("webhook timestamp missing or too old")
        expected = hmac.new(secret.encode(), t.encode() + b"." + body, hashlib.sha256).hexdigest()
        if not hmac.compare_digest(expected, v1):
            raise ValueError("webhook signature doesn't match")
        return json.loads(body)
