#!/bin/bash
# Upload Order of St John credential seals to Azure Blob Storage
# Requires Azure CDN to be set up first

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}[UPLOAD]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[!]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }

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

# Load Azure configuration if available
if [ -f "azure-cdn-config.env" ]; then
    source azure-cdn-config.env
    log_info "Loaded Azure configuration from azure-cdn-config.env"
elif [ -f "infra/scripts/azure-cdn-config.env" ]; then
    source infra/scripts/azure-cdn-config.env
    log_info "Loaded Azure configuration from infra/scripts/azure-cdn-config.env"
fi

# Configuration (can be overridden by environment variables)
STORAGE_ACCOUNT="${AZURE_STORAGE_ACCOUNT:-}"
STORAGE_KEY="${AZURE_STORAGE_KEY:-}"
CONTAINER="${AZURE_STORAGE_CONTAINER:-images}"
PNG_DIR="assets/credential-images/png"

# Check prerequisites
if ! command -v az &> /dev/null; then
    log_error "Azure CLI is not installed"
    echo "Install from: https://docs.microsoft.com/en-us/cli/azure/install-azure-cli"
    exit 1
fi

if ! az account show &> /dev/null; then
    log_error "Not logged in to Azure. Please log in:"
    echo "  az login"
    exit 1
fi

# Check if storage account is configured
if [ -z "${STORAGE_ACCOUNT}" ]; then
    log_error "Azure storage account not configured"
    echo "Run: ./infra/scripts/azure-cdn-setup.sh"
    echo "Or set: AZURE_STORAGE_ACCOUNT=<account-name>"
    exit 1
fi

# Get storage key if not provided
if [ -z "${STORAGE_KEY}" ]; then
    RESOURCE_GROUP="${AZURE_RESOURCE_GROUP:-the-order-cdn-rg}"
    log_info "Retrieving storage account key..."
    STORAGE_KEY=$(az storage account keys list \
        --resource-group "${RESOURCE_GROUP}" \
        --account-name "${STORAGE_ACCOUNT}" \
        --query "[0].value" -o tsv 2>/dev/null || echo "")
    
    if [ -z "${STORAGE_KEY}" ]; then
        log_error "Failed to retrieve storage account key"
        exit 1
    fi
fi

# Check PNG directory
if [ ! -d "${PNG_DIR}" ]; then
    log_error "PNG directory not found: ${PNG_DIR}"
    echo "Run: ./scripts/deploy/prepare-all-credential-seals.sh"
    exit 1
fi

PNG_FILES=($(find "${PNG_DIR}" -name "*.png" -type f))
if [ ${#PNG_FILES[@]} -eq 0 ]; then
    log_error "No PNG files found in ${PNG_DIR}"
    echo "Run: ./scripts/deploy/prepare-all-credential-seals.sh"
    exit 1
fi

log_info "Uploading ${#PNG_FILES[@]} PNG file(s) to Azure Blob Storage"
echo "  Storage Account: ${STORAGE_ACCOUNT}"
echo "  Container: ${CONTAINER}"
echo ""

# Upload each file
UPLOADED=0
FAILED=0

for png_file in "${PNG_FILES[@]}"; do
    filename=$(basename "${png_file}")
    log_info "Uploading: ${filename}"
    
    if az storage blob upload \
        --file "${png_file}" \
        --container-name "${CONTAINER}" \
        --name "${filename}" \
        --account-name "${STORAGE_ACCOUNT}" \
        --account-key "${STORAGE_KEY}" \
        --content-type "image/png" \
        --overwrite \
        -o json &> /dev/null; then
        log_success "  Uploaded: ${filename}"
        ((UPLOADED++))
    else
        log_error "  Failed: ${filename}"
        ((FAILED++))
    fi
done

echo ""
log_info "=== Upload Summary ==="
log_success "Uploaded: ${UPLOADED}"
if [ ${FAILED} -gt 0 ]; then
    log_error "Failed: ${FAILED}"
fi

# Generate URLs
echo ""
log_info "File URLs:"
BLOB_BASE_URL="https://${STORAGE_ACCOUNT}.blob.core.windows.net/${CONTAINER}"
for png_file in "${PNG_FILES[@]}"; do
    filename=$(basename "${png_file}")
    echo "  ${BLOB_BASE_URL}/${filename}"
done

# CDN URL if available
if [ -n "${AZURE_CDN_ENDPOINT_URL:-}" ]; then
    echo ""
    log_info "CDN URLs (once propagated):"
    CDN_BASE_URL="https://${AZURE_CDN_ENDPOINT_URL}/${CONTAINER}"
    for png_file in "${PNG_FILES[@]}"; do
        filename=$(basename "${png_file}")
        echo "  ${CDN_BASE_URL}/${filename}"
    done
fi

echo ""
log_info "Next Steps:"
echo "1. Verify files are accessible:"
echo "   curl -I ${BLOB_BASE_URL}/digital-bank-seal.png"
echo ""
echo "2. Update manifest templates:"
echo "   CDN_BASE_URL=${BLOB_BASE_URL}/ ./scripts/deploy/update-manifest-seal-urls.sh"
echo ""
if [ ${UPLOADED} -eq ${#PNG_FILES[@]} ]; then
    log_success "All files uploaded successfully!"
else
    log_warning "Some files failed to upload. Check errors above."
fi

