#!/usr/bin/env bash
# =============================================================================
# fund-services.sh
#
# Reads the IOTA gas-wallet addresses from running service health endpoints
# and funds each one from the testnet faucet.
#
# Prerequisites:
#   - docker compose services are running (super-certifier-admin, certifier-service)
#   - IOTA CLI installed and switched to testnet
#
# Usage:
#   ./scripts/fund-services.sh
# =============================================================================

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

# ---------------------------------------------------------------------------
# Collect addresses from service health endpoints
# ---------------------------------------------------------------------------

ADDRESSES=()
LABELS=()

echo "==> Network: testnet"
echo "==> Reading gas-wallet addresses from service health endpoints..."
echo ""

read_gas_wallet() {
  local url="$1"
  local attempts="${2:-1}"
  for i in $(seq 1 "$attempts"); do
    local result
    result=$(curl -sf "${url}" 2>/dev/null | \
      python3 -c "import sys,json; print(json.load(sys.stdin)['gas_wallet'])" 2>/dev/null || echo "")
    if [ -n "${result}" ]; then
      echo "${result}"
      return 0
    fi
    [ "$i" -lt "$attempts" ] && sleep 3
  done
  echo ""
}

# Retry up to 10 times (~30s) when called from wizard, once otherwise
RETRIES=1
[ -n "${WIZARD_MODE:-}" ] && RETRIES=10

# -- Super Certifier Admin gas wallet --
SCA_ADDR=$(read_gas_wallet "http://localhost:8083/v1/health" "$RETRIES")
if [ -n "${SCA_ADDR}" ]; then
  echo "  Super Certifier Admin gas wallet: ${SCA_ADDR}"
  ADDRESSES+=("${SCA_ADDR}")
  LABELS+=("super-certifier-admin")
else
  echo "  WARNING: super-certifier-admin not reachable at http://localhost:8083"
  echo "           Start services first: docker compose up -d"
fi

# -- Certifier Service gas wallet --
CS_ADDR=$(read_gas_wallet "http://localhost:8084/v1/health" "$RETRIES")
if [ -n "${CS_ADDR}" ]; then
  echo "  Certifier Service gas wallet:     ${CS_ADDR}"
  ADDRESSES+=("${CS_ADDR}")
  LABELS+=("certifier-service")
else
  echo "  WARNING: certifier-service not reachable at http://localhost:8084"
fi

# echo -e "  ${DIM}(Agent wallets are funded separately during agent setup)${RESET}"

echo ""

if [ ${#ADDRESSES[@]} -eq 0 ]; then
  echo "ERROR: No addresses found. Are services running?"
  echo "       Try: docker compose up -d"
  if [ -n "${WIZARD_MODE:-}" ]; then
    echo ""
    echo "  Skipping wallet funding — you can re-run this script later:"
    echo "  ./scripts/fund-services.sh"
    exit 0
  fi
  exit 1
fi

# ---------------------------------------------------------------------------
# Fund all addresses
# ---------------------------------------------------------------------------

iota client switch --env testnet 2>/dev/null || true

echo "==> Funding ${#ADDRESSES[@]} address(es) from testnet faucet..."
echo ""

for i in "${!ADDRESSES[@]}"; do
  addr="${ADDRESSES[$i]}"
  label="${LABELS[$i]}"
  echo "  Funding ${label} (${addr})..."
  iota client faucet --address "${addr}" 2>&1 | sed 's/^/    /' || \
    echo "    WARNING: faucet request failed for ${addr}"
done

# ANSI colors
BOLD='\033[1m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
DIM='\033[2m'
RESET='\033[0m'

W=106
line() {
    local text="$1"
    local visible
    visible=$(echo -e "$text" | sed 's/\x1b\[[0-9;]*m//g')
    local len=${#visible}
    local pad=$((W - len))
    if [ $pad -lt 0 ]; then pad=0; fi
    printf "${GREEN}║${RESET}%b%*s${GREEN}║${RESET}\n" "$text" "$pad" ""
}
TOP="${GREEN}╔$(printf '═%.0s' $(seq 1 $W))╗${RESET}"
MID="${GREEN}╠$(printf '═%.0s' $(seq 1 $W))╣${RESET}"
BOT="${GREEN}╚$(printf '═%.0s' $(seq 1 $W))╝${RESET}"

echo ""
echo -e "$TOP"
line ""
line "  ${WHITE}${BOLD}All wallets funded${RESET}  ${DIM}(tokens arrive within ~1 minute)${RESET}"
line ""
echo -e "$MID"
line ""
line "  ${BOLD}Funded ${#ADDRESSES[@]} address(es):${RESET}"
for i in "${!ADDRESSES[@]}"; do
    line "    ${CYAN}${LABELS[$i]}${RESET}: ${DIM}${ADDRESSES[$i]}${RESET}"
done
line ""
line "  Verify with: ${DIM}iota client gas${RESET}"
line ""
if [ -z "${WIZARD_MODE:-}" ]; then
    echo -e "$MID"
    line ""
    line "  ${BOLD}Next steps:${RESET}"
    line "    1. Onboard certifier: ${DIM}open http://localhost:5174/register${RESET}"
    line "    2. Approve certifier: ${DIM}open http://localhost:5173${RESET}"
    line "    3. Publish DID:       ${DIM}./scripts/publish-super-certifier.sh${RESET}"
    line "    4. Register agent:    ${DIM}cargo run --bin iota-guardian-agent -- register --ra-url http://localhost:8085${RESET}"
    line ""
fi
echo -e "$BOT"
