#!/bin/bash

# Clipper: A bridge script to fetch clipboard data from the Construct host

# Configuration from environment
HOST_URL="${CONSTRUCT_CLIPBOARD_URL}"
AUTH_TOKEN="${CONSTRUCT_CLIPBOARD_TOKEN}"
AGENT_NAME="${CONSTRUCT_AGENT_NAME}"
DEBUG="${CONSTRUCT_DEBUG:-0}"
CLIPPER_LOG="${CONSTRUCT_CLIPBOARD_LOG:-/tmp/construct-clipper.log}"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] [clipper] $*" >> "$CLIPPER_LOG" 2>/dev/null || true
}

dbg() {
    if [ "$DEBUG" = "1" ]; then
        echo "[clipper] $*" >&2
    fi
    log "$*"
}

if [ -z "$HOST_URL" ]; then
    echo "Error: CONSTRUCT_CLIPBOARD_URL not set" >&2
    exit 1
fi

CALL_NAME=$(basename $0)
log "invoked as=$CALL_NAME agent=$AGENT_NAME url=${HOST_URL:+set} token=${AUTH_TOKEN:+set} args=$*"
dbg "Invoked as=$CALL_NAME agent=$AGENT_NAME args=$*"
TARGET_MIME=""
IS_OUTPUT_MODE=false
REQUESTED_TARGETS=false
PATH_AGENT=false

FILE_PASTE_AGENTS="${CONSTRUCT_FILE_PASTE_AGENTS:-qwen,codex,claude,copilot}"
if [[ ",$FILE_PASTE_AGENTS," == *",$AGENT_NAME,"* ]]; then
    PATH_AGENT=true
fi

# Simple arg parsing for xclip/xsel/wl-paste patterns
NEXT_IS_TYPE=false
for arg in "$@"; do
    if [[ "$NEXT_IS_TYPE" == "true" ]]; then
        TARGET_MIME="$arg"
        NEXT_IS_TYPE=false
        continue
    fi
    if [[ "$arg" == "image/png" ]]; then
        TARGET_MIME="image/png"
    fi
    if [[ "$arg" == "--type" ]] || [[ "$arg" == "-t" ]]; then
        NEXT_IS_TYPE=true
    fi
    if [[ "$arg" == "TARGETS" ]] || [[ "$arg" == "atoms" ]] || [[ "$arg" == "--list-types" ]] || [[ "$arg" == "-l" ]]; then
        REQUESTED_TARGETS=true
    fi
    if [[ "$arg" == "-o" ]] || [[ "$arg" == "--output" ]] || [[ "$arg" == "-p" ]] || [[ "$arg" == "--paste" ]]; then
        IS_OUTPUT_MODE=true
    fi
done

# If TARGETS/atoms was consumed as a -t type value, treat it as a target listing request.
if [[ "$TARGET_MIME" == "TARGETS" ]] || [[ "$TARGET_MIME" == "atoms" ]]; then
    REQUESTED_TARGETS=true
fi

log "parsed: target_mime=${TARGET_MIME:-none} requested_targets=$REQUESTED_TARGETS path_agent=$PATH_AGENT"
dbg "Parsed: target_mime=$TARGET_MIME requested_targets=$REQUESTED_TARGETS path_agent=$PATH_AGENT"

# If agent is asking for available targets, we MUST include image/png
if [[ "$REQUESTED_TARGETS" == "true" ]]; then
    dbg "Returning target list"
    # Always report supported types for the bridge
    echo "TIMESTAMP"
    echo "TARGETS"
    echo "MULTIPLE"
    echo "UTF8_STRING"
    echo "STRING"
    echo "TEXT"
    echo "image/png"
    echo "image/tiff"
    exit 0
fi

TMP_RAW="/tmp/construct-clipboard-raw.png"

fetch_image() {
    curl -s -f \
        -H "X-Construct-Clip-Token: ${AUTH_TOKEN}" \
        "${HOST_URL}/paste?type=image/png" -o "$TMP_RAW"
}

emit_image_bytes() {
    if command -v identify >/dev/null && command -v convert >/dev/null; then
        DIMENSIONS=$(identify -format "%w %h" "$TMP_RAW" 2>/dev/null || true)
        WIDTH=$(echo "$DIMENSIONS" | awk '{print $1}')
        HEIGHT=$(echo "$DIMENSIONS" | awk '{print $2}')
        if [ -n "$WIDTH" ] && [ -n "$HEIGHT" ]; then
            if [ "$WIDTH" -gt 8000 ] || [ "$HEIGHT" -gt 8000 ]; then
                convert "$TMP_RAW" -resize 8000x8000\> png:- 2>/dev/null
                return $?
            fi
        fi
    fi
    cat "$TMP_RAW"
}

emit_image_path() {
    mkdir -p .construct-clipboard 2>/dev/null
    TIMESTAMP=$(date +%s%3N)
    IMG_NAME="clipboard-${TIMESTAMP}.png"
    IMG_PATH="$(pwd)/.construct-clipboard/${IMG_NAME}"
    if cp "$TMP_RAW" "$IMG_PATH"; then
        if [ "$AGENT_NAME" = "codex" ]; then
            echo -n "${IMG_PATH}"
        else
            echo -n "@${IMG_PATH}"
        fi
        return 0
    fi
    return 1
}

# Always try image first; fall back to text if no image and no explicit image request.
if fetch_image; then
    IMG_SIZE=$(wc -c < "$TMP_RAW" 2>/dev/null || echo 0)
    log "image fetched: ${IMG_SIZE} bytes"
    dbg "Image fetched: ${IMG_SIZE} bytes"
    if [[ "$PATH_AGENT" == "true" ]]; then
        log "mode=file-path agent=$AGENT_NAME"
        dbg "Emitting image path"
        emit_image_path
        exit $?
    fi
    log "mode=raw-bytes agent=$AGENT_NAME"
    dbg "Emitting image bytes"
    emit_image_bytes
    exit $?
fi

log "no image from host (fetch failed)"
dbg "No image from host"

if [[ "$TARGET_MIME" == image/* ]]; then
    dbg "Image requested but none available, exit 1"
    exit 1
fi

# Fetch text from host
dbg "Fetching text"
OUTPUT=$(curl -s -f \
    -H "X-Construct-Clip-Token: ${AUTH_TOKEN}" \
    "${HOST_URL}/paste?type=text/plain")

EXIT_CODE=$?

dbg "Text fetch: exit=$EXIT_CODE len=${#OUTPUT}"
echo -n "$OUTPUT"

if [ $EXIT_CODE -eq 22 ]; then
    exit 1
fi

exit $EXIT_CODE
