"""ShipPickup API: client in one file (Python 3.8+, needs only `requests`).

    from shippickup import ShipPickup
    api = ShipPickup()  # key: SHIPPICKUP_API_KEY environment variable

Methods: rates(), create(), get(), cancel(), tracking(), balance(), buy_cheapest(), ShipPickup.verify_webhook().
Every method returns the decoded JSON ("data" and "meta"); an error response raises ShipPickupError.
Documentation: https://api.shippickup.com/docs
"""
import hashlib
import hmac
import os
import time
from urllib.parse import quote

import requests


class ShipPickupError(Exception):
    def __init__(self, status, code, message, details=None):
        super().__init__(message)
        self.status = status  # HTTP status (0 when there was no response)
        self.code = code  # error code from the API, for example rate_expired
        self.details = details or {}  # fields and reasons


class ShipPickup:
    def __init__(self, key=None, base_url=None):
        self.key = key or os.environ.get("SHIPPICKUP_API_KEY", "")
        self.base = (base_url or os.environ.get("SHIPPICKUP_API_URL") or "https://api.shippickup.com/v1").rstrip("/")
        if not self.key:
            raise ShipPickupError(0, "no_key", "Set the SHIPPICKUP_API_KEY environment variable")

    def rates(self, request):
        """Rates for a route and a parcel: {"from": {...}, "to": {...}, "parcel": {...}}."""
        return self._call("POST", "/rates", request)

    def create(self, body, idempotency_key):
        """Buy a label. body: rate_id, from, to, parcel, items. idempotency_key: 16-64 characters, see idempotency_key()."""
        return self._call("POST", "/shipments", body, {"Idempotency-Key": idempotency_key})

    def get(self, order_id):
        """An order by its id or tracking number."""
        return self._call("GET", "/shipments/" + quote(str(order_id), safe=""))

    def cancel(self, order_id, reason=""):
        """Cancel an order; the money returns to the balance."""
        return self._call("POST", "/shipments/" + quote(str(order_id), safe="") + "/cancel", {"reason": reason} if reason else {})

    def tracking(self, order_id):
        """The order and its tracking events (newest first)."""
        return self._call("GET", "/shipments/" + quote(str(order_id), safe="") + "/tracking")

    def balance(self):
        return self._call("GET", "/balance")

    def buy_cheapest(self, body, key):
        """Rates, then the cheapest one is bought. body: from, to, parcel, items (and declared_value_cents)."""
        request = {k: body[k] for k in ("from", "to", "parcel", "declared_value_cents") if k in body}
        rates = self.rates(request)
        if not rates.get("data"):
            raise ShipPickupError(422, "no_rates", "No rates for this route and parcel")
        return self.create({"rate_id": rates["data"][0]["rate_id"], **body}, key)

    @staticmethod
    def idempotency_key(seed):
        """Stable key from your own order number: one order never buys two labels."""
        return "sp-" + hashlib.sha256(str(seed).encode()).hexdigest()[:40]

    @staticmethod
    def verify_webhook(raw_body, signature_header, secret, tolerance_seconds=300):
        """Check the X-Shipto-Signature header of a webhook. raw_body is the body exactly as received (bytes or str)."""
        parts = dict(p.strip().split("=", 1) for p in (signature_header or "").split(",") if "=" in p)
        if not parts.get("t") or not parts.get("v1") or not secret:
            return False
        try:
            if abs(time.time() - int(parts["t"])) > tolerance_seconds:
                return False
        except ValueError:
            return False
        body = raw_body if isinstance(raw_body, bytes) else str(raw_body).encode()
        expected = hmac.new(secret.encode(), parts["t"].encode() + b"." + body, hashlib.sha256).hexdigest()
        return hmac.compare_digest(expected, parts["v1"])

    def _call(self, method, path, body=None, headers=None):
        all_headers = {"Authorization": "Bearer " + self.key, "Accept": "application/json", **(headers or {})}
        try:
            response = requests.request(method, self.base + path, headers=all_headers, json=body, timeout=60)
        except requests.RequestException as e:
            raise ShipPickupError(0, "network_error", str(e))
        try:
            data = response.json()
        except ValueError:
            raise ShipPickupError(response.status_code, "bad_response", "The response is not JSON")
        if response.status_code >= 400 or "error" in data:
            err = data.get("error") or {}
            raise ShipPickupError(response.status_code, err.get("code", "error"), err.get("message", "Error"), err.get("details"))
        return data
