#!/usr/bin/env bash
# Prove the key, then land a sheet of stock as one sync. Needs curl and jq.
#
#   FREEPORT_KEY=fp_test_... ./sync-sheet.sh stock-sheet-template.csv
set -euo pipefail

BASE="${FREEPORT_API:-https://sandbox-api.freeport.gg/v1}"
KEY="${FREEPORT_KEY:?set FREEPORT_KEY to your fp_test_ or fp_live_ key}"
SHEET="${1:-stock-sheet-template.csv}"

auth=(-H "Authorization: Bearer $KEY" -H "Content-Type: application/json")

# 1. Who am I? The answer names the key, its scopes and its environment.
curl -sS "$BASE/ping" "${auth[@]}" | jq .

# 2. Open a sync. Replace mode pauses every line the sheet leaves out.
sync=$(curl -sS -X POST "$BASE/stock/syncs" "${auth[@]}" -d '{"mode":"replace"}' | jq -r .id)
echo "sync $sync"

# 3. Stage the sheet: one JSON line per CSV row, up to a thousand a call.
#    Tiers in the sheet are "min_qty:price;min_qty:price".
lines=$(python3 - "$SHEET" <<'PY'
import csv, json, sys
rows = []
for row in csv.DictReader(open(sys.argv[1], newline='', encoding='utf-8')):
    line = {k: v for k, v in row.items() if v not in ('', None) and k != 'tiers'}
    for key in ('price_per_qty', 'min_qty', 'max_qty', 'stock_qty', 'low_stock_alert_qty', 'delivery_eta_minutes'):
        if key in line: line[key] = int(line[key])
    if row.get('tiers'):
        line['tiers'] = [{'min_qty': int(q), 'price': p} for q, p in (t.split(':') for t in row['tiers'].split(';'))]
    rows.append(line)
print(json.dumps({'lines': rows}))
PY
)
curl -sS -X PUT "$BASE/stock/syncs/$sync/lines" "${auth[@]}" -d "$lines" | jq '.results | group_by(.status) | map({(.[0].status): length}) | add'

# 4. Commit, then wait for the worker. An Idempotency-Key makes the commit safe to retry.
curl -sS -X POST "$BASE/stock/syncs/$sync/commit" "${auth[@]}" -H "Idempotency-Key: commit-$sync" >/dev/null
for _ in $(seq 1 60); do
  status=$(curl -sS "$BASE/stock/syncs/$sync" "${auth[@]}")
  state=$(echo "$status" | jq -r .status)
  if [ "$state" != "committing" ]; then echo "$status" | jq .; break; fi
  sleep 1
done

# 5. Any line that failed says why.
curl -sS "$BASE/stock/syncs/$sync/lines?action=failed" "${auth[@]}" | jq '.data[] | {external_id, error}'
