#!/bin/bash
# R2 Upload Script with Gum UI
# Usage: ./upload.sh <file_path>
#
# === SETUP INSTRUCTIONS ===
#
# 1. Install Gum CLI (Terminal UI toolkit):
#    macOS: brew install gum
#    Linux: bash <(curl -fsSL https://raw.githubusercontent.com/charmbracelet/gum/main/install.sh)
#    More options: https://github.com/charmbracelet/gum#installation
#
# 2. Install Wrangler CLI (Cloudflare tool):
#    npm install -g wrangler
#
# 3. Login to Cloudflare:
#    wrangler login
#
# 4. Create R2 bucket (if it doesn't exist):
#    wrangler r2 bucket create your-bucket-name
#
# 5. Configure this script:
#    - Update BUCKET_NAME with your bucket name
#    - Update CDN_BASE_URL with your CDN domain
#
# 6. Make script executable:
#    chmod +x upload.sh
#
# === USAGE EXAMPLE ===
#
# Upload file: ./upload.sh path/to/file.pdf

# Configuration
BUCKET_NAME="tmp"  # Replace with your bucket name
CDN_BASE_URL="https://tmp.vrypan.net"  # Replace with your CDN URL

# Get file path from first argument
FILE_PATH="$1"

# Check if file path argument is provided
if [ -z "$FILE_PATH" ]; then
    gum style --foreground red --bold "Error: No file path provided"
    gum style --foreground bright-black "Usage: $0 <file_path>"
    exit 1
fi

# Check if file exists
if [ ! -f "$FILE_PATH" ]; then
    gum style --foreground red --bold "Error: File '$FILE_PATH' not found"
    exit 1
fi

# Extract filename from path
FILE_NAME=$(basename "$FILE_PATH")

# Show upload progress
gum spin --spinner meter --spinner.foreground="2" --title "Uploading..." -- \
    wrangler r2 object put "$BUCKET_NAME/$FILE_NAME" -f "$FILE_PATH" --remote

# Check if upload was successful
if [ $? -eq 0 ]; then
    # Generate the CDN URL
    OBJECT_URL="$CDN_BASE_URL/$FILE_NAME"
    
    # Success message with the URL
    CHECK=$(gum style --foreground="2" "✓ ")
    gum join "$CHECK" "Upload successful!"
    
    # Copy URL to clipboard if available
    if command -v pbcopy >/dev/null 2>&1; then
        echo "$OBJECT_URL" | pbcopy
    elif command -v xclip >/dev/null 2>&1; then
        echo "$OBJECT_URL" | xclip -selection clipboard
    fi
    
    CHAIN=$(gum style --foreground="2" "󰌷 ")
    gum join "$CHAIN" "$OBJECT_URL"
else
    gum style --foreground red --bold " Upload failed"
    exit 1
fi
