#!/usr/bin/env bash
# Mint GRU V2 fiat + XAU tokens (wave-1 list) on Chain 138 to the deployer.
# Excludes cUSDT_V2 / cUSDC_V2; add those addresses to the loop if needed.
#
# Usage: ./scripts/mint-c-star-v2-wave1-138.sh [amount_human]
#   Default amount_human = 25000. 6 decimals for all listed tokens.
#   cXAUC_V2 / cXAUT_V2: amount_human is troy ounces (1 token = 1 troy oz Au).
# Requires: PRIVATE_KEY, RPC_URL_138 in .env.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SMOM_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
PROXMOX_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$SMOM_ROOT"
[ -f .env ] && set -a && source .env && set +a
if [[ -z "${PRIVATE_KEY:-}" && -f "${PROXMOX_ROOT}/scripts/lib/load-project-env.sh" ]]; then
  # shellcheck source=../../scripts/lib/load-project-env.sh
  PROJECT_ROOT="$PROXMOX_ROOT" source "${PROXMOX_ROOT}/scripts/lib/load-project-env.sh"
  cd "$SMOM_ROOT"
fi

RPC="${RPC_URL_138:-${RPC_URL:-http://192.168.11.211:8545}}"
# CompliantFiatTokenV2 mint uses ~210k+ gas (compliance + capacity); 100k OOGs.
GAS_LIMIT_MINT="${GAS_LIMIT_MINT:-450000}"
AMOUNT_HUMAN="${1:-25000}"
BASE_UNITS=$((AMOUNT_HUMAN * 1000000))

[ -n "${PRIVATE_KEY:-}" ] || { echo "PRIVATE_KEY not set"; exit 1; }
DEPLOYER=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null) || exit 1

echo "=== Mint c* V2 (wave-1) on Chain 138 ==="
echo "  Deployer: $DEPLOYER  Amount: $AMOUNT_HUMAN tokens each ($BASE_UNITS base)"
echo ""

for pair in \
  "cEURC_V2:0x243e6581Dc8a98d98B92265858b322b193555C81" \
  "cEURT_V2:0x2bAFA83d8fF8BaE9505511998987D0659791605B" \
  "cGBPC_V2:0x707508D223103f5D2d9EFBc656302c9d48878b29" \
  "cGBPT_V2:0xee17c18E10E55ce23F7457D018aAa2Fb1E64B281" \
  "cAUDC_V2:0xfb37aFd415B70C5cEDc9bA58a72D517207b769Bb" \
  "cJPYC_V2:0x2c751bBE4f299b989b3A8c333E0A966cdcA6Fd98" \
  "cCHFC_V2:0x60B7FB8e0DD0Be8595AD12Fe80AE832861Be747c" \
  "cCADC_V2:0xe799033c87fE0CE316DAECcefBE3134CC74b76a9" \
  "cXAUC_V2:0xF0F0F81bE3D033D8586bAfd2293e37eE2f615647" \
  "cXAUT_V2:0x89477E982847023aaB5C3492082cd1bB4b1b9Ef1"; do
  sym="${pair%%:*}"
  addr="${pair#*:}"
  echo -n "Minting $sym... "
  out=$(cast send "$addr" "mint(address,uint256)" "$DEPLOYER" "$BASE_UNITS" \
    --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy --gas-limit "$GAS_LIMIT_MINT" 2>&1) || { echo "FAIL (send)"; echo "$out"; continue; }
  echo "$out"
  txhash=$(echo "$out" | awk '/transactionHash/ {print $2; exit}')
  if [[ -n "$txhash" ]]; then
    st=$(cast receipt "$txhash" status --rpc-url "$RPC" 2>/dev/null | awk '{print $1}' || echo "")
    [[ "$st" == "1" ]] && echo "  receipt: success" || echo "  receipt: check $txhash (parsed status='$st')"
  fi
done
echo "Done."
