#!/usr/bin/env bash

set -e

# Download Azure Architecture Icons
# This script downloads the official Azure Architecture Icons from Microsoft
# Official source: https://docs.microsoft.com/azure/architecture/icons/

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
ASSETS_DIR="${PROJECT_ROOT}/assets"
AZURE_ICONS_DIR="${ASSETS_DIR}/azure-icons"

# Azure Architecture Icons download URLs
# Official source: https://docs.microsoft.com/azure/architecture/icons/
# Note: URLs may change, check the official page for latest version
# Current version: V17 (as of 2024)
AZURE_ICONS_SVG_URL="https://arch-center.azureedge.net/icons/Azure_Public_Service_Icons_V17.zip"
AZURE_ICONS_PNG_URL="https://arch-center.azureedge.net/icons/Azure_Public_Service_Icons_V17_PNG.zip"

# Alternative sources (if primary URLs fail)
AZURE_ICONS_ALTERNATIVE="https://aka.ms/Architecture/icons"
AZURE_ICONS_DOWNLOAD_PAGE="https://docs.microsoft.com/azure/architecture/icons/"

echo "═══════════════════════════════════════════════════════════"
echo "Azure Architecture Icons Download"
echo "═══════════════════════════════════════════════════════════"
echo "Official source: $AZURE_ICONS_DOWNLOAD_PAGE"

# Create directories
mkdir -p "${AZURE_ICONS_DIR}/svg"
mkdir -p "${AZURE_ICONS_DIR}/png"
mkdir -p "${AZURE_ICONS_DIR}/metadata"
mkdir -p "${ASSETS_DIR}/diagrams/architecture"
mkdir -p "${ASSETS_DIR}/diagrams/network"
mkdir -p "${ASSETS_DIR}/diagrams/deployment"
mkdir -p "${ASSETS_DIR}/logos"
mkdir -p "${ASSETS_DIR}/screenshots"
mkdir -p "${ASSETS_DIR}/stencils"

# Check if wget or curl is available
if command -v wget &> /dev/null; then
    DOWNLOAD_CMD="wget"
    DOWNLOAD_FLAGS="-q --show-progress"
elif command -v curl &> /dev/null; then
    DOWNLOAD_CMD="curl"
    DOWNLOAD_FLAGS="-L --progress-bar"
else
    echo "❌ Error: Neither wget nor curl is available. Please install one of them."
    echo "  Ubuntu/Debian: sudo apt-get install wget curl"
    echo "  RHEL/CentOS: sudo yum install wget curl"
    echo "  macOS: brew install wget curl"
    exit 1
fi

# Check if unzip is available
if ! command -v unzip &> /dev/null; then
    echo "❌ Error: unzip is not available. Please install unzip to extract icons."
    echo "  Ubuntu/Debian: sudo apt-get install unzip"
    echo "  RHEL/CentOS: sudo yum install unzip"
    echo "  macOS: brew install unzip"
    echo "Icons can be downloaded manually from: $AZURE_ICONS_DOWNLOAD_PAGE"
    echo "After downloading, extract to: ${AZURE_ICONS_DIR}/"
    exit 1
fi

# Download function
download_file() {
    local url=$1
    local output=$2
    
    echo "  📥 Downloading from: $url"
    if [ "$DOWNLOAD_CMD" == "wget" ]; then
        if wget $DOWNLOAD_FLAGS -O "$output" "$url" 2>&1; then
            return 0
        else
            echo "  ❌ Download failed"
            return 1
        fi
    else
        if curl $DOWNLOAD_FLAGS -o "$output" "$url" 2>&1; then
            return 0
        else
            echo "  ❌ Download failed"
            return 1
        fi
    fi
}

# Extract function - handles nested directory structures
extract_icons() {
    local zip_file=$1
    local target_dir=$2
    local file_pattern=$3
    local icon_type=$4
    
    if [ ! -f "$zip_file" ]; then
        echo "  ❌ Error: ZIP file not found: $zip_file"
        return 1
    fi
    
    echo "  📦 Extracting $icon_type icons..."
    
    # Create temporary directory for extraction
    TEMP_EXTRACT=$(mktemp -d)
    trap "rm -rf $TEMP_EXTRACT" EXIT
    
    # Extract ZIP file to temporary directory
    if ! unzip -q -o "$zip_file" -d "$TEMP_EXTRACT" 2>/dev/null; then
        echo "  ⚠️  Warning: Failed to extract $icon_type icons from $zip_file"
        rm -rf "$TEMP_EXTRACT"
        rm -f "$zip_file"
        return 1
    fi
    
    # Find and copy icon files (handle nested directory structure)
    # Azure icon ZIPs often have nested directories like "Azure_Public_Service_Icons/svg/..."
    # Use a temporary file list to avoid process substitution issues
    local temp_file_list=$(mktemp)
    find "$TEMP_EXTRACT" -type f -name "$file_pattern" 2>/dev/null > "$temp_file_list" || true
    
    local copied=0
    while IFS= read -r file || [ -n "$file" ]; do
        if [ -f "$file" ] && [ -n "$file" ]; then
            # Get just the filename
            filename=$(basename "$file")
            # Copy to target directory (skip if already exists to avoid overwriting)
            if [ ! -f "$target_dir/$filename" ]; then
                if cp "$file" "$target_dir/$filename" 2>/dev/null; then
                    copied=$((copied + 1))
                fi
            fi
        fi
    done < "$temp_file_list"
    rm -f "$temp_file_list"
    
    # Count actual files in target directory
    local final_count=$(find "$target_dir" -maxdepth 1 -name "$file_pattern" -type f 2>/dev/null | wc -l | tr -d ' ')
    
    if [ "$final_count" -gt 0 ]; then
        echo "  ✅ Extracted $final_count $icon_type icons"
    else
        echo "  ⚠️  Warning: No $icon_type icons found in $zip_file"
        echo "  💡 Tip: The ZIP file may have a different structure. Please check manually."
        echo "  💡 You can manually extract the ZIP file and copy icons to: $target_dir"
        echo "  💡 Official download page: https://docs.microsoft.com/azure/architecture/icons/"
    fi
    
    # Cleanup
    rm -rf "$TEMP_EXTRACT"
    rm -f "$zip_file"
    return 0
}

# Download SVG icons
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Downloading SVG Icons"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
TEMP_ZIP="${AZURE_ICONS_DIR}/azure-icons-svg.zip"
if download_file "$AZURE_ICONS_SVG_URL" "$TEMP_ZIP"; then
    extract_icons "$TEMP_ZIP" "${AZURE_ICONS_DIR}/svg" "*.svg" "SVG"
else
    echo "  ❌ Failed to download SVG icons from primary source"
    echo "  💡 Alternative: Manually download from $AZURE_ICONS_DOWNLOAD_PAGE"
    echo "  💡 Or try: $AZURE_ICONS_ALTERNATIVE"
fi

# Download PNG icons
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Downloading PNG Icons"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
TEMP_ZIP="${AZURE_ICONS_DIR}/azure-icons-png.zip"
if download_file "$AZURE_ICONS_PNG_URL" "$TEMP_ZIP"; then
    extract_icons "$TEMP_ZIP" "${AZURE_ICONS_DIR}/png" "*.png" "PNG"
else
    echo "  ❌ Failed to download PNG icons from primary source"
    echo "  💡 Alternative: Manually download from $AZURE_ICONS_DOWNLOAD_PAGE"
    echo "  💡 Or try: $AZURE_ICONS_ALTERNATIVE"
fi

# Create download info
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Creating Metadata"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

SVG_COUNT=$(find "${AZURE_ICONS_DIR}/svg" -maxdepth 1 -name "*.svg" -type f 2>/dev/null | wc -l)
PNG_COUNT=$(find "${AZURE_ICONS_DIR}/png" -maxdepth 1 -name "*.png" -type f 2>/dev/null | wc -l)

cat > "${AZURE_ICONS_DIR}/metadata/download-info.json" << EOF
{
  "download_date": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
  "svg_url": "$AZURE_ICONS_SVG_URL",
  "png_url": "$AZURE_ICONS_PNG_URL",
  "alternative_url": "$AZURE_ICONS_ALTERNATIVE",
  "version": "V17",
  "source": "Microsoft Azure Architecture Center",
  "license": "Microsoft",
  "usage_guidelines": "https://docs.microsoft.com/azure/architecture/icons/",
  "download_page": "$AZURE_ICONS_DOWNLOAD_PAGE",
  "svg_count": $SVG_COUNT,
  "png_count": $PNG_COUNT
}
EOF

echo "  ✅ Metadata created"

# Summary
echo "═══════════════════════════════════════════════════════════"
echo "✅ Azure Architecture Icons Download Complete!"
echo "═══════════════════════════════════════════════════════════"
echo "📁 Icon Locations:"
echo "   SVG: ${AZURE_ICONS_DIR}/svg/"
echo "   PNG: ${AZURE_ICONS_DIR}/png/"
echo "   Metadata: ${AZURE_ICONS_DIR}/metadata/"
echo "📊 Icon Counts:"
echo "   SVG icons: $SVG_COUNT"
echo "   PNG icons: $PNG_COUNT"
echo "📖 Next Steps:"
echo "   1. Review icons in ${AZURE_ICONS_DIR}/"
echo "   2. Use icons in architecture diagrams"
echo "   3. See ${AZURE_ICONS_DIR}/metadata/icon-catalog.md for catalog"
echo "   4. See ${ASSETS_DIR}/README.md for usage instructions"
echo "🔗 For manual download, visit:"
echo "   $AZURE_ICONS_DOWNLOAD_PAGE"
