#!/usr/bin/env bash
# Madely quickstart (curl). Sandbox only: nothing is printed, shipped or charged. No account, no human step.
# Usage: MADELY_BASE=https://api.madely.ai bash quickstart.sh     (needs curl and python3)
set -euo pipefail
BASE="${MADELY_BASE:-https://api.madely.ai}"
json() { python3 -c "import sys,json; d=json.load(sys.stdin); print(eval(sys.argv[1], {'d': d}))" "$1"; }
echo "1. discover";  curl -sf "$BASE/llms.txt" | head -3
echo "2. find a product";  curl -sf "$BASE/v1/products?q=mug&limit=1" | json "d['products'][0]['product_id'] + ' \$' + str(d['products'][0]['price_usd'])"
echo "3. sandbox key"; KEY=$(curl -sf -X POST "$BASE/v1/sandbox/keys" | json "d['api_key']")
echo "4. print spec";  curl -sf "$BASE/v1/products/K04/print-spec" | json "str(d['canvas_px']) + ' @ ' + str(d['dpi']) + ' dpi'"
echo "5. validate a file (declared size)"
curl -sf -X POST "$BASE/v1/print-spec/validate" -H 'Content-Type: application/json' \
  -d '{"product_id":"K04","width_px":2550,"height_px":1155,"format":"png","has_transparency":false}' | json "'valid=' + str(d['valid'])"
echo "6. quote"
QUOTE=$(curl -sf -X POST "$BASE/v1/quotes" -H 'Content-Type: application/json' \
  -d '{"items":[{"product_id":"K04","quantity":24}],"ship_to":{"country":"US","zip":"80202"}}' | json "d['quote_id']")
echo "   quote_id=$QUOTE"
echo "7. test card on file (sandbox card id)"
curl -sf -X POST "$BASE/v1/payment-methods" -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
  -d '{"payment_method_id":"pm_card_visa"}' >/dev/null
echo "8. test order (Idempotency-Key makes a retry safe)"
ORDER=$(curl -sf -X POST "$BASE/v1/orders" -H "Authorization: Bearer $KEY" -H "Idempotency-Key: madely-smoketest-sh-$$" -H 'Content-Type: application/json' -d "{
  \"quote_id\":\"$QUOTE\",\"external_id\":\"madely-smoketest-sh-$$\",\"submit\":true,
  \"payment\":{\"method\":\"card_on_file\"},
  \"ship_to\":{\"name\":\"Test Buyer\",\"address1\":\"1 Test St\",\"city\":\"Denver\",\"state\":\"CO\",\"zip\":\"80202\",\"country\":\"US\"},
  \"items\":[{\"product_id\":\"K04\",\"quantity\":24,\"artwork\":[{\"placement\":\"wrap\",\"url\":\"https://example.com/art/mug.png\",\"width_px\":2550,\"height_px\":1155}]}]}" | json "d['order_id']")
echo "   order_id=$ORDER"
echo "9. status";  curl -sf "$BASE/v1/orders/$ORDER" -H "Authorization: Bearer $KEY" | json "d['status'] + ' total=\$' + str(d['total_usd'])"
