#!/bin/bash
# Image extraction script for agency sites
# Handles: traditional HTML, Next.js/RSC, Sanity, Cloudinary, Mux
# Usage: ./extract-images.sh <url> <output_dir> [max_images]

URL="$1"
OUTPUT_DIR="$2"
MAX_IMAGES="${3:-10}"

if [ -z "$URL" ] || [ -z "$OUTPUT_DIR" ]; then
    echo "Usage: $0 <url> <output_dir> [max_images]"
    echo "Example: $0 https://wearecollins.com/case-studies/primary ./collins 10"
    exit 1
fi

mkdir -p "$OUTPUT_DIR"

echo "🔍 Fetching: $URL"

# Fetch page content once with better headers
PAGE_CONTENT=$(curl -sL "$URL" \
    -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" \
    -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")

# Extract image URLs - multiple patterns
IMAGES=""

# Pattern 1: Standard image URLs in HTML/JSON
STANDARD=$(echo "$PAGE_CONTENT" | \
    grep -oE 'https://[^"'\''()<>\s\\]+\.(jpg|jpeg|png|webp|gif)(\?[^"'\''()<>\s\\]*)?' | \
    sed 's/\\u002F/\//g' | \
    sort -u)

# Pattern 2: Mux video thumbnails (Collins, etc)
MUX=$(echo "$PAGE_CONTENT" | \
    grep -oE 'https://image\.mux\.com/[A-Za-z0-9]+' | \
    sort -u | \
    while read id; do echo "${id}/thumbnail.webp?width=800"; done)

# Pattern 3: Sanity CDN - both escaped and unescaped URLs
SANITY=$(echo "$PAGE_CONTENT" | \
    tr '\\' '\n' | \
    grep -oE 'https://cdn\.sanity\.io/images/[a-z0-9]+/[a-z]+/[a-f0-9]+-[0-9]+x[0-9]+\.(jpg|jpeg|png|webp)' | \
    sort -u)

# Pattern 4: Sanity CDN - from RSC/JSON with escaped slashes
SANITY_RSC=$(echo "$PAGE_CONTENT" | \
    sed 's/\\u002F/\//g' | \
    grep -oE 'https://cdn\.sanity\.io/images/[^"'\''()<>\s]+\.(jpg|jpeg|png|webp)' | \
    sed 's/\\[^/]//g' | \
    sort -u)

# Pattern 5: Cloudinary
CLOUDINARY=$(echo "$PAGE_CONTENT" | \
    grep -oE 'https://res\.cloudinary\.com/[^"'\''()<>\s]+\.(jpg|jpeg|png|webp)' | \
    sort -u)

# Pattern 6: imgix CDN (used by some agencies)
IMGIX=$(echo "$PAGE_CONTENT" | \
    grep -oE 'https://[a-z0-9-]+\.imgix\.net/[^"'\''()<>\s]+' | \
    sort -u)

# Pattern 7: Prismic CDN
PRISMIC=$(echo "$PAGE_CONTENT" | \
    grep -oE 'https://images\.prismic\.io/[^"'\''()<>\s]+\.(jpg|jpeg|png|webp)' | \
    sort -u)

# Combine all patterns
IMAGES=$(echo -e "$STANDARD\n$MUX\n$SANITY\n$SANITY_RSC\n$CLOUDINARY\n$IMGIX\n$PRISMIC" | \
    grep -v '^$' | \
    grep -vE '(favicon|logo|icon|sprite|arrow|button|placeholder)' | \
    sort -u | \
    head -n "$MAX_IMAGES")

if [ -z "$IMAGES" ]; then
    echo "❌ No images found"
    exit 1
fi

COUNT=0
echo "📥 Downloading images to $OUTPUT_DIR"

while IFS= read -r img_url; do
    [ -z "$img_url" ] && continue
    COUNT=$((COUNT + 1))
    
    # Generate unique numbered filename
    EXT=$(echo "$img_url" | grep -oE '\.(jpg|jpeg|png|webp|gif)' | tail -1)
    [ -z "$EXT" ] && EXT=".webp"
    FILENAME="img_$(printf '%02d' $COUNT)$EXT"
    
    echo "  [$COUNT] $FILENAME <- $(echo $img_url | cut -c1-60)..."
    curl -sL "$img_url" -o "$OUTPUT_DIR/$FILENAME" &
    
    # Limit parallel downloads
    [ $((COUNT % 5)) -eq 0 ] && wait
done <<< "$IMAGES"

wait

# Remove empty/tiny files (failed downloads, icons)
find "$OUTPUT_DIR" -type f -size -5000c -delete 2>/dev/null

echo ""
echo "✅ Downloaded:"
ls -la "$OUTPUT_DIR"/ 2>/dev/null | grep -E '\.(jpg|jpeg|png|webp|gif)' | awk '{print "  " $9 " (" $5 " bytes)"}'

TOTAL=$(ls "$OUTPUT_DIR"/*.{jpg,jpeg,png,webp,gif} 2>/dev/null | wc -l | tr -d ' ')
echo ""
echo "📊 Total: $TOTAL images"

# Show preview of what was found
if [ "$TOTAL" -eq 0 ]; then
    echo ""
    echo "💡 Debug: First 3 image-like URLs found in page:"
    echo "$PAGE_CONTENT" | grep -oE 'https://[^"'\''()<>\s\\]+\.(jpg|jpeg|png|webp)' | head -3
fi
