#!/bin/bash
# Update manifest templates with CDN URLs for seal images
# Automates URL updates after CDN deployment

set -euo pipefail

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

log_info() { echo -e "${BLUE}[UPDATE]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[!]${NC} $1"; }

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

MANIFEST_DIR="manifests/entra"
CDN_BASE_URL="${CDN_BASE_URL:-https://cdn.theorder.org/images}"

# Seal to manifest mapping
declare -A SEAL_MAPPING=(
    ["default-manifest-template.json"]="digital-bank-seal.png"
    ["financial-manifest-template.json"]="digital-bank-seal.png"
    ["judicial-manifest-template.json"]="iccc-seal.png"
    ["diplomatic-manifest-template.json"]="diplomatic-security-seal.png"
)

log_info "Updating manifest templates with CDN URLs"
echo "CDN Base URL: ${CDN_BASE_URL}"
echo ""

UPDATED=0
SKIPPED=0

for manifest_file in "${!SEAL_MAPPING[@]}"; do
    manifest_path="${MANIFEST_DIR}/${manifest_file}"
    seal_file="${SEAL_MAPPING[${manifest_file}]}"
    seal_url="${CDN_BASE_URL}/${seal_file}"
    
    if [ ! -f "${manifest_path}" ]; then
        log_warning "Manifest not found: ${manifest_file}"
        ((SKIPPED++))
        continue
    fi
    
    # Check if URL needs updating
    current_url=$(grep -o '"uri": "[^"]*"' "${manifest_path}" | head -1 | cut -d'"' -f4)
    
    if [ "${current_url}" = "${seal_url}" ]; then
        log_info "${manifest_file}: Already has correct URL"
        ((SKIPPED++))
    else
    # Update the URL (remove trailing slash if present to avoid double slashes)
    seal_url_clean=$(echo "${seal_url}" | sed 's|/$||')
    final_url="${seal_url_clean}/${seal_file}"
    if [[ "$OSTYPE" == "darwin"* ]]; then
        # macOS
        sed -i '' "s|\"uri\": \".*seal.*\"|\"uri\": \"${final_url}\"|g" "${manifest_path}"
    else
        # Linux
        sed -i "s|\"uri\": \".*seal.*\"|\"uri\": \"${final_url}\"|g" "${manifest_path}"
    fi
        
        log_success "${manifest_file}: Updated to ${seal_url}"
        ((UPDATED++))
    fi
done

echo ""
log_info "Summary:"
log_success "Updated: ${UPDATED}"
if [ ${SKIPPED} -gt 0 ]; then
    log_info "Skipped: ${SKIPPED}"
fi

if [ ${UPDATED} -gt 0 ]; then
    echo ""
    log_info "To use a different CDN URL, set CDN_BASE_URL:"
    echo "  CDN_BASE_URL=https://your-cdn.com/images ./scripts/deploy/update-manifest-seal-urls.sh"
fi

