#!/bin/bash

# VAPI Call Transcript Processor
# Extracts recent call transcripts and action items from user messages
# Run by heartbeat every hour for overnight autonomy

set -e

# Configuration
VAPI_API_KEY="5158a9b5-8415-4927-bd99-3ae14235de90"
VAPI_BASE_URL="https://api.vapi.ai"
OUTPUT_DIR="/home/ccuser/rateright-growth/rivet/memory/vapi-calls"
LOG_FILE="/home/ccuser/rateright-growth/rivet/memory/vapi-processing.log"
TIMESTAMP=$(date +"%Y-%m-%d_%H-%M-%S")

# Create directories if they don't exist
mkdir -p "$OUTPUT_DIR"

# Function to log messages
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
    echo "$1"
}

# Function to extract action items from text
extract_action_items() {
    local text="$1"
    local call_id="$2"
    
    # Simple pattern matching for action items
    # Look for phrases like "I need", "can you", "please", "remind me", etc.
    echo "$text" | grep -i -E "(need|want|please|can you|could you|remind me|follow up|action item|todo|to do|task)" | head -5
}

# Function to process a single call
process_call() {
    local call_id="$1"
    local call_data="$2"
    
    # Extract call details
    local started_at=$(echo "$call_data" | jq -r '.startedAt // .createdAt // ""')
    local ended_at=$(echo "$call_data" | jq -r '.endedAt // ""')
    local status=$(echo "$call_data" | jq -r '.status // ""')
    local phone_number=$(echo "$call_data" | jq -r '.phoneNumber // ""')
    local assistant_id=$(echo "$call_data" | jq -r '.assistantId // ""')
    
    # Get transcript
    local transcript_response=$(curl -s -X GET \
        -H "Authorization: Bearer $VAPI_API_KEY" \
        -H "Content-Type: application/json" \
        "$VAPI_BASE_URL/call/$call_id/transcript")
    
    local transcript=$(echo "$transcript_response" | jq -r '.transcript // .text // ""')
    
    if [ -z "$transcript" ] || [ "$transcript" = "null" ]; then
        log "No transcript found for call $call_id"
        return 1
    fi
    
    # Create output file
    local output_file="$OUTPUT_DIR/call_${call_id}_${TIMESTAMP}.md"
    
    # Write call details
    {
        echo "# VAPI Call Transcript"
        echo ""
        echo "## Call Details"
        echo "- **Call ID:** $call_id"
        echo "- **Started:** $started_at"
        echo "- **Ended:** $ended_at"
        echo "- **Status:** $status"
        echo "- **Phone Number:** $phone_number"
        echo "- **Assistant ID:** $assistant_id"
        echo "- **Processed:** $(date)"
        echo ""
        echo "## Transcript"
        echo ""
        echo '```'
        echo "$transcript"
        echo '```'
        echo ""
        echo "## Action Items"
        echo ""
    } > "$output_file"
    
    # Extract and write action items
    local action_items=$(extract_action_items "$transcript" "$call_id")
    if [ -n "$action_items" ]; then
        echo "$action_items" | while read -r item; do
            echo "- $item" >> "$output_file"
        done
    else
        echo "*No action items detected*" >> "$output_file"
    fi
    
    echo "" >> "$output_file"
    echo "---" >> "$output_file"
    
    log "Processed call $call_id -> $output_file"
    echo "$output_file"
}

# Main processing
log "Starting VAPI call processing at $(date)"

log "Fetching recent calls (last 50)"

# Fetch recent calls (limit 50, most recent first)
CALLS_RESPONSE=$(curl -s -X GET \
    -H "Authorization: Bearer $VAPI_API_KEY" \
    -H "Content-Type: application/json" \
    "$VAPI_BASE_URL/call?limit=50")

# Calculate timestamp for 2 hours ago (in seconds since epoch)
TWO_HOURS_AGO_SEC=$(date -u -d '2 hours ago' +%s)

# Check if we got a valid response
if echo "$CALLS_RESPONSE" | jq -e '.calls' > /dev/null 2>&1; then
    # VAPI returns { "calls": [...] }
    CALLS_ARRAY=$(echo "$CALLS_RESPONSE" | jq '.calls')
    CALL_COUNT=$(echo "$CALLS_ARRAY" | jq '. | length')
    log "Found $CALL_COUNT total calls"
    
    # Process each call from last 2 hours
    PROCESSED_COUNT=0
    for i in $(seq 0 $((CALL_COUNT - 1))); do
        CALL_DATA=$(echo "$CALLS_ARRAY" | jq ".[$i]")
        CALL_ID=$(echo "$CALL_DATA" | jq -r '.id')
        CALL_CREATED=$(echo "$CALL_DATA" | jq -r '.createdAt // .startedAt // ""')
        
        # Convert call timestamp to seconds since epoch
        if [ -n "$CALL_CREATED" ] && [ "$CALL_CREATED" != "null" ]; then
            # Try to parse ISO timestamp
            CALL_TIME_SEC=$(date -u -d "$CALL_CREATED" +%s 2>/dev/null || echo "0")
            
            # Only process calls from last 2 hours
            if [ "$CALL_TIME_SEC" -ge "$TWO_HOURS_AGO_SEC" ]; then
                if [ -n "$CALL_ID" ] && [ "$CALL_ID" != "null" ]; then
                    process_call "$CALL_ID" "$CALL_DATA" && PROCESSED_COUNT=$((PROCESSED_COUNT + 1))
                fi
            fi
        fi
    done
    
    log "Successfully processed $PROCESSED_COUNT calls from last 2 hours"
elif echo "$CALLS_RESPONSE" | jq -e 'type == "array"' > /dev/null 2>&1; then
    # Some endpoints might return array directly
    CALL_COUNT=$(echo "$CALLS_RESPONSE" | jq '. | length')
    log "Found $CALL_COUNT total calls"
    
    # Process each call from last 2 hours
    PROCESSED_COUNT=0
    for i in $(seq 0 $((CALL_COUNT - 1))); do
        CALL_DATA=$(echo "$CALLS_RESPONSE" | jq ".[$i]")
        CALL_ID=$(echo "$CALL_DATA" | jq -r '.id')
        CALL_CREATED=$(echo "$CALL_DATA" | jq -r '.createdAt // .startedAt // ""')
        
        # Convert call timestamp to seconds since epoch
        if [ -n "$CALL_CREATED" ] && [ "$CALL_CREATED" != "null" ]; then
            # Try to parse ISO timestamp
            CALL_TIME_SEC=$(date -u -d "$CALL_CREATED" +%s 2>/dev/null || echo "0")
            
            # Only process calls from last 2 hours
            if [ "$CALL_TIME_SEC" -ge "$TWO_HOURS_AGO_SEC" ]; then
                if [ -n "$CALL_ID" ] && [ "$CALL_ID" != "null" ]; then
                    process_call "$CALL_ID" "$CALL_DATA" && PROCESSED_COUNT=$((PROCESSED_COUNT + 1))
                fi
            fi
        fi
    done
    
    log "Successfully processed $PROCESSED_COUNT calls from last 2 hours"
else
    log "No calls found or error fetching calls"
    log "Response preview: $(echo "$CALLS_RESPONSE" | head -100)"
fi

log "VAPI call processing completed at $(date)"
echo "Processed $PROCESSED_COUNT calls"