#!/bin/bash
# clippaste-image - Paste clipboard image to temp file for Claude Code
# Usage: clippaste-image [output-path]
#
# This script extracts image data from the clipboard and saves it to a file.
# Works with both Wayland (wl-paste) and X11 (xclip).
#
# Examples:
#   clippaste-image                    # Saves to /tmp/clipboard-image.png
#   clippaste-image ~/screenshot.png   # Saves to specified path
#   clippaste-image -                  # Outputs file path to stdout only
#
# Claude Code Integration:
#   Simply press Ctrl+V in Claude Code CLI, or use this script directly.

set -e

OUTPUT_PATH="${1:-/tmp/clipboard-image.png}"
STDOUT_ONLY=false

if [[ "$OUTPUT_PATH" == "-" ]]; then
    OUTPUT_PATH="/tmp/clipboard-image-$(date +%s).png"
    STDOUT_ONLY=true
fi

# Create temp directory if needed
mkdir -p "$(dirname "$OUTPUT_PATH")"

# Try Wayland first (wl-paste)
if command -v wl-paste &> /dev/null; then
    # Check if Wayland display is available
    if [[ -n "$WAYLAND_DISPLAY" ]] || wl-paste --type text &> /dev/null; then
        # Try to get image from clipboard
        if wl-paste --type image/png > "$OUTPUT_PATH" 2>/dev/null; then
            # Verify we got actual image data (not empty)
            if [[ -s "$OUTPUT_PATH" ]]; then
                if [[ "$STDOUT_ONLY" == true ]]; then
                    echo "$OUTPUT_PATH"
                else
                    echo "✓ Image saved to: $OUTPUT_PATH"
                    echo "  Size: $(du -h "$OUTPUT_PATH" | cut -f1)"
                fi
                exit 0
            fi
        fi
    fi
fi

# Fallback to X11 (xclip)
if command -v xclip &> /dev/null; then
    if [[ -n "$DISPLAY" ]]; then
        # Try to get image from X11 clipboard
        if xclip -selection clipboard -t image/png -o > "$OUTPUT_PATH" 2>/dev/null; then
            if [[ -s "$OUTPUT_PATH" ]]; then
                if [[ "$STDOUT_ONLY" == true ]]; then
                    echo "$OUTPUT_PATH"
                else
                    echo "✓ Image saved to: $OUTPUT_PATH"
                    echo "  Size: $(du -h "$OUTPUT_PATH" | cut -f1)"
                fi
                exit 0
            fi
        fi
    fi
fi

# No image found in clipboard
if [[ "$STDOUT_ONLY" == true ]]; then
    exit 1
else
    echo "✗ No image found in clipboard" >&2
    echo ""
    echo "Tips:"
    echo "  - Take a screenshot first (gnome-screenshot -a -c)"
    echo "  - Copy an image from your file manager or browser"
    echo "  - On Wayland: ensure wl-paste can access your compositor"
    echo "  - On X11: ensure xclip can access the X server"
    exit 1
fi
