#!/usr/bin/env bash
set +x
set -euo pipefail
umask 077
: "${ANTHROPIC_API_KEY:?Set a workspace-scoped API key from the linked Console organization first}"
# لا تشغّله إلا عندما تقرر إرسال طلب مدفوع واحد. لم ينفذه هذا الدليل.
# يُمرر المفتاح إلى curl عبر الإدخال القياسي، ولا يظهر في وسائط الأمر.
http_code=$(curl --disable --silent --show-error \
  --connect-timeout 10 --max-time 60 \
  --dump-header response.headers \
  --output response.json --write-out '%{http_code}' \
  --config - <<EOF
url = "https://api.anthropic.com/v1/messages"
request = "POST"
header = "Authorization: Bearer ${ANTHROPIC_API_KEY}"
header = "anthropic-version: 2026-10-21"
header = "content-type: application/json"
data-binary = "@request.json"
EOF
)
printf 'HTTP %s\n' "$http_code"
python3 - <<'PY'
import json
from pathlib import Path

body = json.loads(Path('response.json').read_text())
if body.get('type') == 'error' or 'error' in body:
    print('error_type:', body.get('error', {}).get('type', 'unknown'))
    raise SystemExit(1)

print('model:', body.get('model'))
print('stop_reason:', body.get('stop_reason'))
print('text:', '\n'.join(block.get('text', '')
      for block in body.get('content', []) if block.get('type') == 'text'))
print('usage:', json.dumps(body.get('usage', {}), ensure_ascii=False))

wanted = {'request-id', 'anthropic-organization-id', 'anthropic-workspace-id'}
for line in Path('response.headers').read_text(errors='replace').splitlines():
    name, sep, value = line.partition(':')
    if sep and name.lower() in wanted:
        print(name.lower()+':', value.strip())
PY
[[ "$http_code" == 200 ]]
