"""velik.ai Platform API — Python 3.9+ (requests). Run: VELIK_API_KEY=vk_… python3 python.py"""
import os
import sys

import requests

BASE = os.environ.get("VELIK_BASE_URL", "https://velik.ai")
KEY = os.environ.get("VELIK_API_KEY") or sys.exit("set VELIK_API_KEY")
S = requests.Session()
S.headers["Authorization"] = f"Bearer {KEY}"


class VelikError(Exception):
    def __init__(self, status, payload):
        err = (payload or {}).get("error", {})
        super().__init__(f"{status} {err.get('code')}: {err.get('message')}")
        self.status, self.code, self.details = status, err.get("code"), err.get("details")


def velik(method, path, json=None, dry_run=False):
    headers = {"X-Velik-Dry-Run": "1"} if dry_run else {}
    r = S.request(method, BASE + path, json=json, headers=headers, timeout=30)
    if r.status_code >= 400:
        raise VelikError(r.status_code, r.json() if r.content else None)
    return r.json()


def new_orders():
    """Every order in status `new`, following the keyset cursor."""
    cursor = None
    while True:
        params = {"status": "new", "limit": 100}
        if cursor:
            params["cursor"] = cursor
        page = velik("GET", "/api/v1/orders", json=None) if False else S.get(
            BASE + "/api/v1/orders", params=params, timeout=30
        ).json()
        yield from page["data"]
        if not page["has_more"]:
            return
        cursor = page["next_cursor"]


for order in new_orders():
    print(f"#{order['number']} {order['customer']['name']} {order['total']} {order['shipping']['city']}")
    # velik("PATCH", f"/api/v1/orders/{order['id']}", json={"status": "processing"})
    # velik("PATCH", f"/api/v1/orders/{order['id']}",
    #       json={"tracking_number": "WMS-2026-000123", "courier": "Speedy", "status": "shipped"})
    break

# Dry run of a stock delivery (validates, writes nothing):
# velik("POST", "/api/v1/inventory/movements", dry_run=True,
#       json={"product_id": "<product uuid>", "type": "delivery", "qty": 12, "unit_cost": 2.5})
