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

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./lib/api_client.sh
source "$SCRIPT_DIR/lib/api_client.sh"

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

if [[ -z "$TASK_ID" ]]; then
  echo "Usage: $0 <task-id> [attachment-index]"
  exit 1
fi

if ! command -v jq >/dev/null 2>&1; then
  echo "jq is required. Install with: brew install jq"
  exit 1
fi

RESPONSE=$(api_call GET "/tasks?taskId=$(urlencode "$TASK_ID")&include=detail")
ATTACHMENTS=$(echo "$RESPONSE" | jq '.tasks[0].attachments // []')
COUNT=$(echo "$ATTACHMENTS" | jq 'length')

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

ATTACHMENT=$(echo "$ATTACHMENTS" | jq ".[$ATTACHMENT_INDEX]")
if [[ "$ATTACHMENT" == "null" || -z "$ATTACHMENT" ]]; then
  echo "Attachment index $ATTACHMENT_INDEX not found."
  exit 1
fi

FILENAME=$(echo "$ATTACHMENT" | jq -r '.name // "attachment.bin"')
MIME_TYPE=$(echo "$ATTACHMENT" | jq -r '.type // "application/octet-stream"')
DATA_URL=$(echo "$ATTACHMENT" | jq -r '.dataUrl // .url // empty')

if [[ -z "$DATA_URL" ]]; then
  echo "Attachment does not contain dataUrl/url content"
  exit 1
fi

BASE64_CONTENT=$(echo "$DATA_URL" | sed 's/^data:[^;]*;base64,//')
TMP_FILE="/tmp/gantt-attachment-$(date +%s)-$FILENAME"
echo "$BASE64_CONTENT" | base64 -d > "$TMP_FILE"

echo "Attachment: $FILENAME"
echo "Type: $MIME_TYPE"
echo "Size: $(stat -f%z "$TMP_FILE" 2>/dev/null || stat -c%s "$TMP_FILE") bytes"
echo ""

if [[ "$MIME_TYPE" == text/* ]] || [[ "$FILENAME" == *.md ]] || [[ "$FILENAME" == *.txt ]] || [[ "$FILENAME" == *.json ]]; then
  cat "$TMP_FILE"
else
  echo "Binary file extracted to: $TMP_FILE"
  echo "Open with: open '$TMP_FILE'"
fi
