#!/usr/bin/env bash
# Mint CompliantFiatToken Tether-style ISO complements on Chain 138 (cAUDT, cJPYT, cCHFT, cCADT).
# Uses addresses from smom-dbis-138/.env: CAUDT_ADDRESS_138, CJPYT_ADDRESS_138, CCHFT_ADDRESS_138, CCADT_ADDRESS_138.
#
# Default: random whole-number amount per token between 26_000_000 and 85_000_000 (6 decimals).
# Override: ./scripts/mint-compliant-fiat-tether-iso-138.sh <amount_human>  (same amount for all four)
#
# Requires: PRIVATE_KEY (minter/deployer), RPC. Skips any address unset or zero.
# Requires: cast (foundry).

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"

if [[ -f .env ]]; then
  set -a && source .env && set +a
fi
if [[ -z "${PRIVATE_KEY:-}" && -f "${PROXMOX_ROOT}/scripts/lib/load-project-env.sh" ]]; then
  # shellcheck disable=SC1090
  PROJECT_ROOT="$PROXMOX_ROOT" source "${PROXMOX_ROOT}/scripts/lib/load-project-env.sh"
  cd "$SMOM_ROOT"
fi

RPC="${RPC_URL_138:-${CHAIN138_RPC:-${RPC_URL:-http://192.168.11.211:8545}}}"
GAS_LIMIT_MINT="${GAS_LIMIT_MINT:-400000}"

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

if [[ -n "${1:-}" ]]; then
  AMOUNT_HUMAN="$1"
elif command -v shuf >/dev/null 2>&1; then
  AMOUNT_HUMAN=$(shuf -i 26000000-85000000 -n 1)
elif command -v python3 >/dev/null 2>&1; then
  AMOUNT_HUMAN=$(python3 -c 'import random; print(random.randint(26_000_000, 85_000_000))')
else
  echo "Install coreutils (shuf) or python3 for random mint amounts, or pass amount_human as \$1" >&2
  exit 1
fi
BASE_UNITS=$((AMOUNT_HUMAN * 1000000))

echo "=== Mint Tether ISO complements (Chain 138) ==="
echo "  Deployer: $DEPLOYER"
echo "  Amount:   $AMOUNT_HUMAN tokens each ($BASE_UNITS base units)"
echo "  RPC:      $RPC"
echo ""

for pair in \
  "cAUDT:${CAUDT_ADDRESS_138:-}" \
  "cJPYT:${CJPYT_ADDRESS_138:-}" \
  "cCHFT:${CCHFT_ADDRESS_138:-}" \
  "cCADT:${CCADT_ADDRESS_138:-}"; do
  sym="${pair%%:*}"
  addr="${pair#*:}"
  if [[ -z "$addr" || "$addr" == "0x0000000000000000000000000000000000000000" ]]; then
    echo "Skip $sym (address not set in .env)"
    continue
  fi
  echo -n "Mint $sym ($addr)... "
  if cast send "$addr" "mint(address,uint256)" "$DEPLOYER" "$BASE_UNITS" \
    --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy --gas-limit "$GAS_LIMIT_MINT" 2>/dev/null; then
    echo OK
  else
    echo FAIL
  fi
done
echo "Done."
