#!/bin/bash
# Complete automation: Prepare all Order of St John credential seals
# Converts SVG to PNG, validates, and prepares for deployment

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"; }

cd "$(dirname "$0")/../.."

SVG_DIR="assets/credential-images/svg"
PNG_DIR="assets/credential-images/png"
SIZES=(200 400 800)

log_info "=== Order of St John Seal Preparation ==="
echo ""

# Check for SVG files
if [ ! -d "${SVG_DIR}" ]; then
    log_error "SVG directory not found: ${SVG_DIR}"
    exit 1
fi

SVG_FILES=($(find "${SVG_DIR}" -name "*.svg" | sort))
if [ ${#SVG_FILES[@]} -eq 0 ]; then
    log_error "No SVG files found in ${SVG_DIR}"
    exit 1
fi

log_success "Found ${#SVG_FILES[@]} SVG file(s)"
echo ""

# Create PNG directory
mkdir -p "${PNG_DIR}"

# Function to convert SVG to PNG
convert_svg() {
    local svg_file=$1
    local output_file=$2
    local width=$3
    local height=$4
    
    local filename=$(basename "${svg_file}" .svg)
    
    # Try ImageMagick first
    if command -v convert &> /dev/null; then
        convert -background none -resize "${width}x${height}" "${svg_file}" "${output_file}" 2>/dev/null && return 0
    fi
    
    # Try Inkscape
    if command -v inkscape &> /dev/null; then
        inkscape "${svg_file}" --export-filename="${output_file}" --export-width="${width}" --export-height="${height}" --export-type=png 2>/dev/null && return 0
    fi
    
    # Try Node.js with sharp
    if command -v node &> /dev/null; then
        # Try to find sharp in various locations
        SHARP_PATH=""
        if node -e "require('sharp')" 2>/dev/null; then
            SHARP_PATH="sharp"
        elif [ -f "packages/auth/node_modules/sharp/package.json" ]; then
            SHARP_PATH="packages/auth/node_modules/sharp"
        elif [ -f "node_modules/sharp/package.json" ]; then
            SHARP_PATH="node_modules/sharp"
        fi
        
        if [ -n "${SHARP_PATH}" ]; then
            # Use absolute path for SVG file
            SVG_ABS=$(cd "$(dirname "${svg_file}")" && pwd)/$(basename "${svg_file}")
            OUT_ABS=$(cd "$(dirname "${output_file}")" && pwd)/$(basename "${output_file}")
            
            node -e "
            const path = require('path');
            const sharp = require('${SHARP_PATH}');
            sharp('${SVG_ABS}')
              .resize(${width}, ${height})
              .png()
              .toFile('${OUT_ABS}')
              .then(() => process.exit(0))
              .catch((err) => { console.error(err); process.exit(1); });
            " 2>/dev/null && return 0
        fi
    fi
    
    log_warning "No conversion tool available (ImageMagick, Inkscape, or sharp)"
    return 1
}

# Check if converter is available
HAS_CONVERTER=false
if command -v convert &> /dev/null || command -v inkscape &> /dev/null; then
    HAS_CONVERTER=true
elif command -v node &> /dev/null; then
    # Check for sharp in various locations
    if node -e "require('sharp')" 2>/dev/null || \
       [ -f "packages/auth/node_modules/sharp/package.json" ] || \
       [ -f "node_modules/sharp/package.json" ]; then
        HAS_CONVERTER=true
    fi
fi

# Convert each SVG to multiple PNG sizes
CONVERTED=0
FAILED=0

for svg_file in "${SVG_FILES[@]}"; do
    filename=$(basename "${svg_file}" .svg)
    log_info "Processing: ${filename}.svg"
    
    # Convert to each size
    for size in "${SIZES[@]}"; do
        png_file="${PNG_DIR}/${filename}-${size}x${size}.png"
        
        if convert_svg "${svg_file}" "${png_file}" "${size}" "${size}"; then
            log_success "  Created: ${filename}-${size}x${size}.png"
            ((CONVERTED++))
        else
            if [ "${HAS_CONVERTER:-false}" = "false" ]; then
                log_warning "  Skipped: ${filename}-${size}x${size}.png (no conversion tool)"
            else
                log_warning "  Failed to create: ${filename}-${size}x${size}.png"
            fi
            ((FAILED++))
        fi
    done
    
    # Also create default 200x200 without size suffix (for convenience)
    default_png="${PNG_DIR}/${filename}.png"
    if convert_svg "${svg_file}" "${default_png}" 200 200; then
        log_success "  Created: ${filename}.png (default)"
    fi
    
    echo ""
done

# Validate PNG files
log_info "Validating PNG files..."
VALID_PNG=0
INVALID_PNG=0

for png_file in "${PNG_DIR}"/*.png; do
    if [ -f "${png_file}" ]; then
        if file "${png_file}" | grep -q "PNG"; then
            ((VALID_PNG++))
        else
            log_warning "Invalid PNG: $(basename "${png_file}")"
            ((INVALID_PNG++))
        fi
    fi
done

# Generate file manifest
log_info "Generating file manifest..."
cat > "${PNG_DIR}/MANIFEST.txt" << EOF
Order of St John Credential Seals - File Manifest
Generated: $(date -u +"%Y-%m-%d %H:%M:%S UTC")

SVG Source Files:
$(for f in "${SVG_FILES[@]}"; do echo "  - $(basename "$f")"; done)

PNG Files Generated:
$(find "${PNG_DIR}" -name "*.png" -type f | sort | sed 's|.*/|  - |')

Total Files:
  SVG: ${#SVG_FILES[@]}
  PNG: ${VALID_PNG}
  
Recommended Sizes:
  - 200x200px: For credential logos (Entra VerifiedID)
  - 400x400px: For high-resolution displays
  - 800x800px: For print/embossing

CDN Upload:
  Upload all PNG files to: https://cdn.theorder.org/images/
  Ensure HTTPS and public access
  Update manifest templates with CDN URLs
EOF

log_success "File manifest created: ${PNG_DIR}/MANIFEST.txt"

# Generate upload script
log_info "Generating CDN upload script..."
cat > "${PNG_DIR}/upload-to-cdn.sh" << 'UPLOAD_EOF'
#!/bin/bash
# Upload credential seal PNG files to CDN
# Configure CDN details before running

set -euo pipefail

CDN_BASE_URL="${CDN_BASE_URL:-https://cdn.theorder.org/images}"
CDN_DIR="${CDN_DIR:-./}"

echo "Uploading PNG files to CDN..."
echo "CDN Base URL: ${CDN_BASE_URL}"
echo ""

# This is a template - customize based on your CDN provider
# Examples: AWS S3, Azure Blob Storage, Cloudflare, etc.

for png_file in *.png; do
    if [ -f "${png_file}" ]; then
        echo "Would upload: ${png_file} to ${CDN_BASE_URL}/${png_file}"
        # Add your CDN upload command here
        # Example for AWS S3:
        # aws s3 cp "${png_file}" "s3://your-bucket/images/${png_file}" --acl public-read
        # Example for Azure:
        # az storage blob upload --file "${png_file}" --container-name images --name "${png_file}" --account-name your-account
    fi
done

echo ""
echo "After uploading, update manifest templates with CDN URLs"
UPLOAD_EOF

chmod +x "${PNG_DIR}/upload-to-cdn.sh"
log_success "Upload script created: ${PNG_DIR}/upload-to-cdn.sh"

# Generate validation report
log_info "Generating validation report..."
cat > "${PNG_DIR}/VALIDATION_REPORT.txt" << EOF
Order of St John Seals - Validation Report
Generated: $(date -u +"%Y-%m-%d %H:%M:%S UTC")

Conversion Results:
  Successful: ${CONVERTED}
  Failed: ${FAILED}

PNG Validation:
  Valid PNG files: ${VALID_PNG}
  Invalid files: ${INVALID_PNG}

File Sizes:
$(for png in "${PNG_DIR}"/*.png; do
    if [ -f "${png}" ]; then
        size=$(du -h "${png}" | cut -f1)
        echo "  $(basename "${png}"): ${size}"
    fi
done)

Recommendations:
  - Use 200x200px PNG for Entra VerifiedID credentials
  - Ensure all files are under 100KB for optimal performance
  - Verify images are publicly accessible via HTTPS
  - Test images in credential wallets before production use
EOF

log_success "Validation report created: ${PNG_DIR}/VALIDATION_REPORT.txt"

# Summary
echo ""
log_info "=== Summary ==="
log_success "SVG files processed: ${#SVG_FILES[@]}"
log_success "PNG files created: ${CONVERTED}"
if [ ${FAILED} -gt 0 ]; then
    log_warning "Failed conversions: ${FAILED}"
fi
log_success "Valid PNG files: ${VALID_PNG}"

echo ""
log_info "Next steps:"
echo "1. Review PNG files in: ${PNG_DIR}/"
echo "2. Check validation report: ${PNG_DIR}/VALIDATION_REPORT.txt"
echo "3. Upload to CDN: ${PNG_DIR}/upload-to-cdn.sh"
echo "4. Update manifest templates with CDN URLs"
echo "5. Test credentials with new seal images"

log_success "Seal preparation complete!"

