#!/bin/bash
# Sales Prospector - HOA Lead Generation (STABLE VERSION)

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
STATE_DIR="${SCRIPT_DIR}/state"
LOG_DIR="${SCRIPT_DIR}/logs"
mkdir -p "$STATE_DIR" "$LOG_DIR"

LOG_FILE="${LOG_DIR}/prospector-$(date +%Y%m%d).log"
STATE_FILE="${STATE_DIR}/prospector-state.json"

METROS=("Charlotte NC" "Atlanta GA" "Orlando FL" "Phoenix AZ")

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# Ensure state exists
if [[ ! -f "$STATE_FILE" ]]; then
    echo '{"currentMetroIndex":0}' > "$STATE_FILE"
fi

log "=== Sales Prospector Started ==="
log "Throttle: 10min business hours / 5min overnight"

cycle=0
while true; do
    cycle=$((cycle + 1))
    
    # Get current metro
    idx=$(jq -r '.currentMetroIndex // 0' "$STATE_FILE")
    metro="${METROS[$idx]}"
    
    log "CYCLE $cycle: $metro"
    
    # Search queries
    log "Searching: $metro HOA board"
    
    # Calculate throttle
    h=$(date +%H)
    if [[ $h -ge 9 && $h -lt 18 ]]; then
        delay=600  # 10 minutes
    else
        delay=300  # 5 minutes
    fi
    
    log "Sleeping ${delay}s (throttle)..."
    sleep $delay
    
    # Next metro
    next=$(( (idx + 1) % 4 ))
    jq --arg n "$next" '.currentMetroIndex = ($n | tonumber)' "$STATE_FILE" > "${STATE_FILE}.tmp" && mv "${STATE_FILE}.tmp" "$STATE_FILE"
    
    log "Cycle complete"
done

trap 'log "Shutdown"; exit 0' INT TERM
