#!/bin/bash
# View attachment from a gantt board task
# Usage: ./view-attachment.sh <task-id> [attachment-index]

SUPABASE_URL="https://qnatchrjlpehiijwtreh.supabase.co"
SERVICE_KEY="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InFuYXRjaHJqbHBlaGlpand0cmVoIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc3MTY0MDQzNiwiZXhwIjoyMDg3MjE2NDM2fQ.rHoc3NfL59S4lejU4-ArSzox1krQkQG-TnfXb6sslm0"

HEADERS=(-H "apikey: $SERVICE_KEY" -H "Authorization: Bearer $SERVICE_KEY" -H "Content-Type: application/json")

TASK_ID="$1"
ATTACHMENT_INDEX="${2:-0}"

if [[ -z "$TASK_ID" ]]; then
    echo "Usage: $0 <task-id> [attachment-index]"
    echo ""
    echo "Examples:"
    echo "  $0 33ebc71e-7d40-456c-8f98-bb3578d2bb2b       # View first attachment"
    echo "  $0 33ebc71e-7d40-456c-8f98-bb3578d2bb2b 0      # View first attachment (explicit)"
    exit 1
fi

# Fetch task with attachments
echo "Fetching task attachments..."
TASK_DATA=$(curl -s "$SUPABASE_URL/rest/v1/tasks?id=eq.$TASK_ID&select=title,attachments" "${HEADERS[@]}")

# Extract attachments array
ATTACHMENTS=$(echo "$TASK_DATA" | jq -r 'if type == "array" then (.[0].attachments // []) else (.attachments // []) end')
ATTACHMENT_COUNT=$(echo "$ATTACHMENTS" | jq 'length')

if [[ "$ATTACHMENT_COUNT" -eq 0 ]]; then
    echo "❌ No attachments found on this task."
    exit 1
fi

echo ""
echo "Found $ATTACHMENT_COUNT attachment(s):"
echo "$ATTACHMENTS" | jq -r '.[] | "  - \(.name) (\(.size) bytes, \(.type))"'
echo ""

# Get the requested attachment
ATTACHMENT=$(echo "$ATTACHMENTS" | jq -r ".[$ATTACHMENT_INDEX]")
if [[ "$ATTACHMENT" == "null" ]]; then
    echo "❌ Attachment index $ATTACHMENT_INDEX not found."
    exit 1
fi

FILENAME=$(echo "$ATTACHMENT" | jq -r '.name')
MIME_TYPE=$(echo "$ATTACHMENT" | jq -r '.type')
DATA_URL=$(echo "$ATTACHMENT" | jq -r '.url')

# Extract base64 content from data URL (remove data:mime/type;base64, prefix)
BASE64_CONTENT=$(echo "$DATA_URL" | sed 's/^data:[^;]*;base64,//')

# Decode to temp file
TEMP_FILE="/tmp/gantt-attachment-$(date +%s)-$FILENAME"
echo "$BASE64_CONTENT" | base64 -d > "$TEMP_FILE"

echo "📎 Attachment: $FILENAME"
echo "📋 Type: $MIME_TYPE"
echo "📊 Size: $(stat -f%z "$TEMP_FILE") bytes"
echo ""
echo "--- CONTENT ---"
echo ""

# Display based on type
if [[ "$MIME_TYPE" == text/* ]] || [[ "$FILENAME" == *.md ]] || [[ "$FILENAME" == *.txt ]]; then
    cat "$TEMP_FILE"
else
    echo "(Binary file - saved to: $TEMP_FILE)"
    echo "Open with: open '$TEMP_FILE'"
fi

echo ""
echo "---------------"

# Clean up temp file
rm -f "$TEMP_FILE"
