#!/bin/bash
# save-artifact - save a result to the artifact panel
# usage: save-artifact --type <type> --name <name> [--file <path>] [--description <desc>]
#        cat data.json | save-artifact --type json --name "data"
#
# types: table, chart, csv, json, image, markdown, dashboard

set -e

# Parse arguments
TYPE=""
NAME=""
FILE=""
DESCRIPTION=""

while [[ $# -gt 0 ]]; do
  case $1 in
    --type) TYPE="$2"; shift 2 ;;
    --name) NAME="$2"; shift 2 ;;
    --file) FILE="$2"; shift 2 ;;
    --description) DESCRIPTION="$2"; shift 2 ;;
    *) echo "Unknown option: $1" >&2; exit 1 ;;
  esac
done

if [ -z "$TYPE" ] || [ -z "$NAME" ]; then
  echo "Usage: save-artifact --type <type> --name <name> [--file <path>] [--description <desc>]" >&2
  echo "Types: table, chart, csv, json, image, markdown, dashboard" >&2
  exit 1
fi

# Get content from file or stdin
if [ -n "$FILE" ]; then
  if [ ! -f "$FILE" ]; then
    echo "File not found: $FILE" >&2
    exit 1
  fi
  # Check if SVG (text format, no encoding needed)
  if [[ "$FILE" == *.svg ]]; then
    CONTENT=$(cat "$FILE")
  # Base64 encode binary files (PNG images)
  elif [[ "$TYPE" == "chart" || "$TYPE" == "image" ]]; then
    CONTENT=$(base64 -w 0 "$FILE" 2>/dev/null || base64 "$FILE" | tr -d '\n')
  else
    CONTENT=$(cat "$FILE")
  fi
else
  # Read from stdin
  if [[ "$TYPE" == "chart" || "$TYPE" == "image" ]]; then
    CONTENT=$(base64 -w 0 2>/dev/null || base64 | tr -d '\n')
  else
    CONTENT=$(cat)
  fi
fi

# Get conversation ID from environment
if [ -z "$CONVERSATION_ID" ]; then
  echo "Error: CONVERSATION_ID not set" >&2
  exit 1
fi

# Generate artifact ID (simple timestamp + random)
ARTIFACT_ID="$(date +%s)$(head -c 8 /dev/urandom | od -An -tx1 | tr -d ' \n')"

# Determine mime type
case $TYPE in
  table|json) MIME="application/json" ;;
  csv) MIME="text/csv" ;;
  markdown) MIME="text/markdown" ;;
  image|chart)
    if [[ "$FILE" == *.svg ]]; then
      MIME="image/svg+xml"
    else
      MIME="image/png"
    fi
    ;;
  *) MIME="text/plain" ;;
esac

# API endpoint
API_URL="${API_URL:-https://agent.sublimated.com}"

# Build JSON payload
PAYLOAD=$(jq -n \
  --arg id "$ARTIFACT_ID" \
  --arg conversationId "$CONVERSATION_ID" \
  --arg type "$TYPE" \
  --arg name "$NAME" \
  --arg description "$DESCRIPTION" \
  --arg content "$CONTENT" \
  --arg mimeType "$MIME" \
  '{
    id: $id,
    conversationId: $conversationId,
    type: $type,
    name: $name,
    description: (if $description == "" then null else $description end),
    content: $content,
    mimeType: $mimeType
  }'
)

# Also save to local filesystem for collectArtifacts
ARTIFACT_DIR="/artifacts/$CONVERSATION_ID"
mkdir -p "$ARTIFACT_DIR"
echo "$PAYLOAD" > "$ARTIFACT_DIR/$ARTIFACT_ID.json"

# Call API
RESPONSE=$(curl -s -X POST "$API_URL/internal/save-artifact" \
  -H "Content-Type: application/json" \
  -d "$PAYLOAD")

# Output result
echo "$RESPONSE" | jq '.'
