"""TCS-i reference client for Python (3.8+, standard library only).

Everything an in-house WMS or ERP needs to work with TCS-i, in one file you
can copy into your system. Docs: https://www.tcs-i.com/api-docs/

    from tcsi import TcsI
    tcs = TcsI("your-key")                      # make one in Console > Integrations
    tcs.sync_boxes([{"id": "M", "length": 40, "width": 30, "height": 20}])
    tcs.sync_products([{"sku": "TEE", "length": 30, "width": 20, "height": 2, "is_flexible": True}])
    tcs.create_order("SO-1", [{"sku": "TEE", "quantity": 2}])
    plan = tcs.recommend("SO-1")                # the box(es), and a 3D view link for the packer
    tcs.packed("SO-1", packed_by="ann")         # what it went in: TCS-i learns from it
    for event in tcs.events():                  # or receive them: verify_webhook below
        ...

Errors raise TcsIError with the API's code and message. Lists page by cursor
for you. Every call is free except recommend (a box recommendation), and that
on a free account for its first 50 jobs a month.
"""

import hashlib
import hmac
import json
import time
import urllib.error
import urllib.parse
import urllib.request

__version__ = "1.0.0"
API = "https://api.tcs-i.com"


class TcsIError(Exception):
    def __init__(self, status, code, message, details=None):
        super().__init__(f"{status} {code}: {message}")
        self.status, self.code, self.message, self.details = status, code, message, details


class TcsI:
    def __init__(self, key, base_url=API, timeout=60):
        self.key, self.base_url, self.timeout = key, base_url.rstrip("/"), timeout

    # --- plumbing -------------------------------------------------------------------
    def request(self, method, path, body=None, params=None, _attempt=0):
        query = {k: v for k, v in (params or {}).items() if v is not None}
        url = self.base_url + path + ("?" + urllib.parse.urlencode(query) if query else "")
        data = json.dumps(body).encode() if body is not None else None
        req = urllib.request.Request(url, data=data, method=method, headers={
            "x-api-key": self.key, "Content-Type": "application/json", "Accept": "application/json",
            "User-Agent": f"tcsi-python/{__version__}"})
        try:
            with urllib.request.urlopen(req, timeout=self.timeout) as res:
                text = res.read().decode() or "null"
        except urllib.error.HTTPError as e:
            # A key may make 600 calls a minute: on 429, wait as the API says and carry on (3 times at most).
            if e.code == 429 and _attempt < 3:
                try:
                    wait = float(e.headers.get("Retry-After") or 1)
                except (TypeError, ValueError):
                    wait = 1.0
                time.sleep(min(max(wait, 0.0), 60.0))
                return self.request(method, path, body, params, _attempt + 1)
            raw = e.read().decode()
            try:
                err = json.loads(raw).get("error") or {}
            except ValueError:
                err = {}
            raise TcsIError(e.code, err.get("code", "error"), err.get("message", raw[:300]), err.get("details")) from None
        return json.loads(text)

    def pages(self, path, params=None):
        """Every item of a list, following next_cursor."""
        params = dict(params or {})
        while True:
            page = self.request("GET", path, params=params)
            for item in page.get("data") or []:
                yield item
            if not page.get("next_cursor") or not page.get("data"):
                return
            params["cursor"] = page["next_cursor"]

    @staticmethod
    def _id(value):
        return urllib.parse.quote(str(value), safe="")

    # --- your data ------------------------------------------------------------------
    def me(self):
        return self.request("GET", "/v1/me")

    def sync_boxes(self, boxes, dimension_unit="cm", weight_unit="kg", batch_size=500):
        """Create or replace boxes by id (up to 500 a call; more are sent in batches)."""
        return [self.request("POST", "/v1/boxes/bulk", {"boxes": boxes[i:i + batch_size],
                                                        "dimension_unit": dimension_unit, "weight_unit": weight_unit})
                for i in range(0, len(boxes), batch_size)]

    def sync_products(self, products, dimension_unit="cm", batch_size=500):
        """Create or update products by SKU (up to 500 a call; more are sent in batches)."""
        return [self.request("POST", "/v1/products/bulk", {"products": products[i:i + batch_size],
                                                           "dimension_unit": dimension_unit})
                for i in range(0, len(products), batch_size)]

    def boxes(self, **params):
        return self.pages("/v1/boxes", params)

    def archive_product(self, sku, brand=None):
        """Retire a product you no longer sell: kept, out of lists; sync it again to bring it back."""
        self.request("DELETE", f"/v1/products/{self._id(sku)}", params={"brand": brand})

    def products(self, **params):
        """e.g. products(updated_since="2026-11-12T00:00:00Z")"""
        return self.pages("/v1/products", params)

    # --- orders ---------------------------------------------------------------------
    def create_order(self, order_id, lines, order_number=None, brand=None, note=None):
        """lines: [{"sku": "TEE", "quantity": 2}, ...]"""
        body = {"order_id": order_id, "lines": lines, "order_number": order_number, "brand": brand, "note": note}
        return self.request("POST", "/v1/orders", {k: v for k, v in body.items() if v is not None})

    def recommend(self, order_id, brand=None):
        """The box(es) for the order: { status, recommendation: { boxes, view_url, request_id }, solution }."""
        return self.request("POST", f"/v1/orders/{self._id(order_id)}/recommend", params={"brand": brand})

    def packed(self, order_id, boxes=None, packed_by=None, brand=None):
        """What it went in. No boxes: the recommended ones. boxes: [{"box_id": "M"}, ...]"""
        body = {k: v for k, v in {"boxes": boxes, "packed_by": packed_by}.items() if v is not None}
        return self.request("POST", f"/v1/orders/{self._id(order_id)}/packed", body, params={"brand": brand})

    def cancel(self, order_id, brand=None):
        return self.request("POST", f"/v1/orders/{self._id(order_id)}/cancel", params={"brand": brand})

    def order(self, order_id, brand=None):
        return self.request("GET", f"/v1/orders/{self._id(order_id)}", params={"brand": brand})

    def pack_input(self, lines, brand=None):
        """The complete POST /pack body for these lines, from your data in TCS-i (free)."""
        return self.request("POST", "/v1/pack-input", {"lines": lines, "brand": brand})

    def pack(self, body):
        """POST /pack: the pure engine (items, boxes and everything in the body)."""
        return self.request("POST", "/pack", body)

    # --- changes from TCS-i -----------------------------------------------------------
    def latest_event_id(self):
        """Where the feed is now: pass it as after= to read only what happens next."""
        return self.request("GET", "/v1/events", params={"after": "now"})["next_cursor"]

    def events(self, after=None, types=None):
        """Events oldest first, from after (an event id). Keep the last id you handled
        and pass it next time. types: e.g. ["product.updated"]."""
        params = {"after": after, "types": ",".join(types) if types else None}
        while True:
            page = self.request("GET", "/v1/events", params=params)
            for event in page["data"]:
                yield event
            if not page["data"]:
                return
            params["after"] = page["next_cursor"]

    def add_webhook(self, url, events=None, description=None):
        """Returns the webhook with its whole secret: store it (shown once)."""
        return self.request("POST", "/v1/webhooks", {k: v for k, v in
                                                     {"url": url, "events": events, "description": description}.items()
                                                     if v is not None})

    def test_webhook(self, webhook_id):
        return self.request("POST", f"/v1/webhooks/{self._id(webhook_id)}/test")

    # --- the assistant, rules, insights ------------------------------------------------
    def assistant(self, brand=None):
        return self.request("GET", "/v1/assistant", params={"brand": brand})

    def packing_preferences(self, **changes):
        """No arguments: read them. With some: change them, e.g. fragile_on_top=False."""
        if changes:
            return self.request("PATCH", "/v1/packing-preferences", changes)
        return self.request("GET", "/v1/packing-preferences")

    def insights(self, days=7, brand=None):
        return self.request("GET", "/v1/insights/packing", params={"days": days, "brand": brand})

    # --- everything else the console does (anything not here: self.request) -------------
    def setup(self):
        """Where the account stands: what's linked, what's missing, and the calls left to make."""
        return self.request("GET", "/v1/setup")

    def delete_box(self, box_id, brand=None):
        return self.request("DELETE", f"/v1/boxes/{self._id(box_id)}", params={"brand": brand})

    def recommendations(self, **params):
        """Every box recommended and what was packed, newest first, e.g. status="packed", brand="Voxy"."""
        if "from_" in params:
            params["from"] = params.pop("from_")
        return self.pages("/v1/recommendations", params)

    def report(self, name, **params):
        """summary, costs, box-usage, box-usage/monthly, products, brands, brand-activity, product-health, data-problems."""
        return self.request("GET", f"/v1/reports/{name}", params=params)

    def cost_settings(self, **changes):
        """No arguments: read them. With some: change them, e.g. labour={"wage_per_hour": 18}."""
        if changes:
            return self.request("PUT", "/v1/cost-settings", changes)
        return self.request("GET", "/v1/cost-settings")


def verify_webhook(secret, signature_header, raw_body, tolerance=300, now=None):
    """True if a delivery came from TCS-i: TCS-Signature is t=<unix>,v1=<hex HMAC-SHA256 of "t.body">.
    Pass the raw body exactly as received (bytes or str). Refuses signatures older than 5 minutes."""
    if isinstance(raw_body, bytes):
        raw_body = raw_body.decode()
    try:
        parts = dict(p.split("=", 1) for p in (signature_header or "").split(","))
        timestamp = int(parts["t"])
    except (ValueError, KeyError):
        return False
    if abs((now or time.time()) - timestamp) > tolerance:
        return False
    expected = hmac.new(secret.encode(), f"{timestamp}.{raw_body}".encode(), hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts.get("v1", ""))
