#!/bin/bash
# Convert SVG files to PNG for Entra VerifiedID credential images
# Supports multiple conversion methods

set -euo pipefail

GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

usage() {
    echo "Usage: $0 <input.svg> [output.png] [width] [height]"
    echo ""
    echo "Converts SVG to PNG for Entra VerifiedID credential images"
    echo ""
    echo "Arguments:"
    echo "  input.svg   - Input SVG file"
    echo "  output.png  - Output PNG file (default: input.png)"
    echo "  width       - Output width in pixels (default: 200)"
    echo "  height      - Output height in pixels (default: 200)"
    echo ""
    echo "Requirements:"
    echo "  - ImageMagick (convert) OR"
    echo "  - Inkscape OR"
    echo "  - Node.js with sharp package"
    exit 1
}

if [ $# -lt 1 ]; then
    usage
fi

INPUT_FILE="$1"
OUTPUT_FILE="${2:-${INPUT_FILE%.svg}.png}"
WIDTH="${3:-200}"
HEIGHT="${4:-200}"

if [ ! -f "${INPUT_FILE}" ]; then
    log_error "Input file not found: ${INPUT_FILE}"
    exit 1
fi

log_info "Converting ${INPUT_FILE} to ${OUTPUT_FILE} (${WIDTH}x${HEIGHT})"

# Try ImageMagick first
if command -v convert &> /dev/null; then
    log_info "Using ImageMagick..."
    convert -background none -resize "${WIDTH}x${HEIGHT}" "${INPUT_FILE}" "${OUTPUT_FILE}"
    log_success "Conversion complete: ${OUTPUT_FILE}"
    exit 0
fi

# Try Inkscape
if command -v inkscape &> /dev/null; then
    log_info "Using Inkscape..."
    inkscape "${INPUT_FILE}" --export-filename="${OUTPUT_FILE}" --export-width="${WIDTH}" --export-height="${HEIGHT}" --export-type=png
    log_success "Conversion complete: ${OUTPUT_FILE}"
    exit 0
fi

# Try Node.js with sharp
if command -v node &> /dev/null; then
    log_info "Trying Node.js conversion..."
    node -e "
    const fs = require('fs');
    const sharp = require('sharp');
    sharp('${INPUT_FILE}')
      .resize(${WIDTH}, ${HEIGHT})
      .png()
      .toFile('${OUTPUT_FILE}')
      .then(() => console.log('Conversion complete'))
      .catch(err => {
        console.error('Sharp not available or error:', err.message);
        process.exit(1);
      });
    " 2>/dev/null && log_success "Conversion complete: ${OUTPUT_FILE}" && exit 0
fi

log_error "No conversion tool found. Install one of:"
echo "  - ImageMagick: sudo apt-get install imagemagick"
echo "  - Inkscape: sudo apt-get install inkscape"
echo "  - sharp (Node.js): pnpm add sharp"
exit 1

