#!/usr/bin/env bash
# MoneyTools Transcripts with plain curl (dTelecom-compatible, pay per file via x402, no prepaid credits).
#   export X402_PRIVATE_KEY=0x...   # Base wallet with USDC; needs: pip install "x402[evm]" eth-account
#   curl -sO https://speech.moneytools.dev/examples/x402_sign.py
#   bash transcribe.sh meeting.mp3 [srt|vtt|txt|json]
set -euo pipefail
FILE="$1"; FMT="${2:-srt}"
BASE="${TRANSCRIPTS_BASE:-https://speech.moneytools.dev}"
KEY="sh-$(date +%s)-$RANDOM"   # Idempotency-Key: reuse it for the paid retry

# 1) Unpaid upload -> HTTP 402 + PAYMENT-REQUIRED header with the exact price for this file
PR=$(curl -s -D - -o /tmp/mt-402.json -X POST "$BASE/v1/transcriptions/jobs" \
  -H "Idempotency-Key: $KEY" -F "file=@$FILE" | tr -d '\r' | awk -F': ' 'tolower($1)=="payment-required"{print $2}')
echo "quote: $(python3 -c 'import json;q=json.load(open("/tmp/mt-402.json"))["quote"];print(q["startedMinutes"],"min =",q["amountUsd"],"USDC")')" >&2

# 2) Sign locally (nothing is sent yet)
SIG=$(python3 x402_sign.py "$PR")

# 3) Same request + PAYMENT-SIGNATURE -> 202 {id, job_token, status_url}
curl -s -X POST "$BASE/v1/transcriptions/jobs" -H "Idempotency-Key: $KEY" \
  -H "PAYMENT-SIGNATURE: $SIG" -F "file=@$FILE" -o /tmp/mt-job.json
grep -q '"job_token"' /tmp/mt-job.json || { echo "not accepted:" >&2; python3 -c 'import json;j=json.load(open("/tmp/mt-job.json"));print(j.get("error"),j.get("message",""))' >&2; exit 1; }
ID=$(python3 -c 'import json;print(json.load(open("/tmp/mt-job.json"))["id"])')
TOKEN=$(python3 -c 'import json;print(json.load(open("/tmp/mt-job.json"))["job_token"])')

# 4) Poll until completed, then fetch the subtitles
while :; do
  S=$(curl -s -H "Authorization: Bearer $TOKEN" "$BASE/v1/transcriptions/jobs/$ID" | python3 -c 'import json,sys;print(json.load(sys.stdin)["status"])')
  echo "status: $S" >&2
  [ "$S" = completed ] || [ "$S" = failed ] && break
  sleep 15
done
curl -s -H "Authorization: Bearer $TOKEN" "$BASE/v1/transcriptions/jobs/$ID?format=$FMT"
