#!/bin/bash
# Bland AI Outbound Call Script
# Usage: ./bland-call.sh "+1XXXXXXXXXX" "Your task/prompt here"

set -e

# Load API key from .env
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [ -f "$SCRIPT_DIR/.env" ]; then
    export $(grep -v '^#' "$SCRIPT_DIR/.env" | xargs)
fi

if [ -z "$BLAND_API_KEY" ]; then
    echo "Error: BLAND_API_KEY not set"
    exit 1
fi

PHONE_NUMBER="$1"
TASK="$2"
VOICE="${3:-Josh}"  # Default voice, can override

if [ -z "$PHONE_NUMBER" ] || [ -z "$TASK" ]; then
    echo "Usage: $0 <phone_number> <task> [voice]"
    echo "Example: $0 '+17275022300' 'Ask if they are open tomorrow and offer same-day dry cleaning' 'Derek'"
    exit 1
fi

echo "📞 Initiating Bland AI call..."
echo "   To: $PHONE_NUMBER"
echo "   Voice: $VOICE"
echo ""

RESPONSE=$(curl -s -X POST "https://api.bland.ai/v1/calls" \
    -H "Authorization: $BLAND_API_KEY" \
    -H "Content-Type: application/json" \
    -d "{
        \"phone_number\": \"$PHONE_NUMBER\",
        \"task\": \"$TASK\",
        \"voice\": \"$VOICE\",
        \"wait_for_greeting\": true,
        \"max_duration\": 5,
        \"record\": true
    }")

echo "$RESPONSE" | jq . 2>/dev/null || echo "$RESPONSE"

# Extract call ID for status checking
CALL_ID=$(echo "$RESPONSE" | jq -r '.call_id // empty')
if [ -n "$CALL_ID" ]; then
    echo ""
    echo "✅ Call initiated! ID: $CALL_ID"
    echo "   Check status: curl -H \"Authorization: $BLAND_API_KEY\" https://api.bland.ai/v1/calls/$CALL_ID"
fi
