"""An in-house WMS working with TCS-i, end to end. Run it with a key from Console > Integrations:

    TCSI_KEY=... python example_inhouse_wms.py            the whole loop, once
    TCSI_WEBHOOK_SECRET=whsec_... python example_inhouse_wms.py serve 8080
                                                           receive webhooks (POST /tcs-i/events)

The loop, as your system would do it, each at its moment:
  1. your box list changes          -> sync_boxes
  2. a product is created or changed -> sync_products
  3. an order is released            -> create_order, then recommend: show the box to the packer
  4. the packer finishes             -> packed (TCS-i learns from what really happened)
  5. TCS-i changes something         -> events (or a webhook): e.g. a size the assistant fixed
"""

import json
import os
import sys
import time
from http.server import BaseHTTPRequestHandler, HTTPServer

from tcsi import API, TcsI, verify_webhook

# Everything the example makes goes under its own brand, so your real catalogue,
# orders and packing are never touched. In your system, use your own brands (or
# none, for a single-brand account).
BRAND = "TCS-i example"

BOXES = [{"id": "CARTON-S", "name": "Small carton", "length": 25, "width": 20, "height": 10},
         {"id": "CARTON-M", "name": "Medium carton", "length": 40, "width": 30, "height": 20, "max_weight": 15},
         {"id": "MAILER", "name": "Poly mailer", "length": 35, "width": 25, "height": 3, "is_mailer": True}]
PRODUCTS = [{"sku": "TEE-M", "name": "T-shirt M", "length": 30, "width": 20, "height": 2, "is_flexible": True,
             "bag_allowed": True},
            {"sku": "MUG-01", "name": "Mug", "length": 12, "width": 9, "height": 10, "is_fragile": True}]


def loop(tcs):
    me = tcs.me()
    print("Account:", me.get("name") or me.get("account"), f"({me.get('key_kind')} key)")
    start = tcs.latest_event_id()                                         # events from here on
    print("Boxes:", tcs.sync_boxes([{**b, "brand": BRAND} for b in BOXES])[0])
    print("Products:", tcs.sync_products([{**p, "brand": BRAND} for p in PRODUCTS])[0])
    order_id = f"EXAMPLE-{int(time.time())}"
    tcs.create_order(order_id, [{"sku": "TEE-M", "quantity": 2}, {"sku": "MUG-01", "quantity": 1}], brand=BRAND)
    plan = tcs.recommend(order_id, brand=BRAND)
    rec = plan["recommendation"]
    print("Box for", order_id + ":", ", ".join(f"{b.get('name') or b['id']} ({b.get('items')} items)" for b in rec["boxes"]))
    print("Show the packer:", rec.get("view_url"))
    packed = tcs.packed(order_id, packed_by="example", brand=BRAND)
    print("Packed:", packed["status"])
    for event in tcs.events(after=start):
        print("Event:", event["type"], json.dumps(event["data"])[:120])
    print(f"Done. The example's boxes, products and order are under the brand {BRAND!r}.")
    return order_id


def serve(port, secret):
    class Handler(BaseHTTPRequestHandler):
        def do_POST(self):
            raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))
            if not verify_webhook(secret, self.headers.get("TCS-Signature"), raw):
                self.send_response(401)
                self.end_headers()
                return
            event = json.loads(raw)
            # Do your work here, e.g. a product.updated by the assistant: update the product's size.
            print("Webhook:", event["type"], event["id"], json.dumps(event["data"])[:120], flush=True)
            self.send_response(204)                        # any 2xx: delivered
            self.end_headers()

        def log_message(self, *args):
            pass
    print(f"Listening on :{port} for TCS-i webhooks", flush=True)
    HTTPServer(("", port), Handler).serve_forever()


if __name__ == "__main__":
    if sys.argv[1:2] == ["serve"]:
        serve(int(sys.argv[2]) if len(sys.argv) > 2 else 8080, os.environ["TCSI_WEBHOOK_SECRET"])
    else:
        loop(TcsI(os.environ["TCSI_KEY"], os.environ.get("TCSI_URL", API)))
