#!/usr/bin/env bash
# Transfer 10,000 (6 decimals) of each fiat c* from deployer to recipient. Excludes cXAUC/cXAUT.
#
# Usage:
#   source ../scripts/lib/load-project-env.sh   # from repo root, or ensure PRIVATE_KEY + RPC_URL_138
#   ./scripts/transfer-fiat-c-star-to-recipient-138.sh
#   RECIPIENT=0x... AMOUNT_HUMAN=10000 ./scripts/transfer-fiat-c-star-to-recipient-138.sh
#   DRY_RUN=1 ./scripts/transfer-fiat-c-star-to-recipient-138.sh
#
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$PROJECT_ROOT"
[ -f .env ] && set -a && source .env && set +a
[ -f "$PROJECT_ROOT/../.env" ] && set -a && source "$PROJECT_ROOT/../.env" && set +a

RPC="${RPC_URL_138:-${RPC_URL:-http://192.168.11.211:8545}}"
RECIPIENT="${RECIPIENT:-0xCD386a74ab9E6378C8B5B44299CF595119647989}"
AMOUNT_HUMAN="${AMOUNT_HUMAN:-10000}"
BASE_UNITS=$((AMOUNT_HUMAN * 1000000))

if [ -n "${PRIVATE_KEY:-}" ]; then
  DEPLOYER="$(cast wallet address "$PRIVATE_KEY")" || exit 1
else
  DEPLOYER="(set PRIVATE_KEY)"
fi
if [ -z "${PRIVATE_KEY:-}" ] && [ -z "${DRY_RUN:-}" ]; then
  echo "PRIVATE_KEY not set (use DRY_RUN=1 to print commands only)"
  exit 1
fi

# Fiat compliant c* only (canonical Chain 138) — not XAU
declare -a TOKENS=(
  "cUSDT:0x93E66202A11B1772E55407B32B44e5Cd8eda7f22"
  "cUSDC:0xf22258f57794CC8E06237084b353Ab30fFfa640b"
  "cEURC:0x8085961F9cF02b4d800A3c6d386D31da4B34266a"
  "cEURT:0xdf4b71c61E5912712C1Bdd451416B9aC26949d72"
  "cGBPC:0x003960f16D9d34F2e98d62723B6721Fb92074aD2"
  "cGBPT:0x350f54e4D23795f86A9c03988c7135357CCaD97c"
  "cAUDC:0xD51482e567c03899eecE3CAe8a058161FD56069D"
  "cJPYC:0xEe269e1226a334182aace90056EE4ee5Cc8A6770"
  "cCHFC:0x873990849DDa5117d7C644f0aF24370797C03885"
  "cCADC:0x54dBd40cF05e15906A2C21f600937e96787f5679"
)

echo "=== Transfer fiat c* (Chain 138) ==="
echo "  RPC:       $RPC"
echo "  Deployer:  $DEPLOYER"
echo "  Recipient: $RECIPIENT"
echo "  Amount:    $AMOUNT_HUMAN tokens each ($BASE_UNITS base)"
echo ""

for pair in "${TOKENS[@]}"; do
  sym="${pair%%:*}"
  addr="${pair#*:}"
  if [ -n "${DRY_RUN:-}" ]; then
    echo "[dry-run] cast send $addr transfer $RECIPIENT $BASE_UNITS  # $sym"
    continue
  fi
  echo -n "Transfer $sym... "
  if cast send "$addr" "transfer(address,uint256)" "$RECIPIENT" "$BASE_UNITS" \
    --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy --gas-limit 200000; then
    echo OK
  else
    echo FAIL
    exit 1
  fi
done
echo "Done."
