#!/usr/bin/env bash
# Mint cXAUC and/or cXAUT on Chain 138 to the minter (owner) address.
# Amounts are always in TROY OUNCES (1 full token = 1 troy oz Au; 6 decimals).
#
# Usage:
#   ./scripts/mint-xau-chain138.sh <troy_ounces>              # mint both tokens (default)
#   ./scripts/mint-xau-chain138.sh <troy_ounces> --cxauc-only
#   ./scripts/mint-xau-chain138.sh <troy_ounces> --cxaut-only
#   MINT_TO=0x... ./scripts/mint-xau-chain138.sh <troy_ounces>   # recipient (default: deployer from PRIVATE_KEY)
#   DRY_RUN=1 ./scripts/mint-xau-chain138.sh 100
#
# Requires: PRIVATE_KEY, RPC_URL_138 (or RPC_URL) in .env
#
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

CXAUC="0x290E52a8819A4fbD0714E517225429aA2B70EC6b"
CXAUT="0x94e408E26c6FD8F4ee00b54dF19082FDA07dC96E"
RPC="${RPC_URL_138:-${RPC_URL:-http://192.168.11.211:8545}}"
GAS_LIMIT="${GAS_LIMIT:-200000}"

[ -n "${PRIVATE_KEY:-}" ] || { echo "PRIVATE_KEY not set"; exit 1; }

OZ="${1:-}"
[ -n "$OZ" ] || { echo "Usage: $0 <troy_ounces> [--cxauc-only|--cxaut-only]"; exit 1; }
shift || true

DO_CXAUC=1
DO_CXAUT=1
for a in "$@"; do
  case "$a" in
    --cxauc-only) DO_CXAUC=1; DO_CXAUT=0 ;;
    --cxaut-only) DO_CXAUC=0; DO_CXAUT=1 ;;
    *) echo "Unknown option: $a"; exit 1 ;;
  esac
done

BASE_UNITS="$(python3 -c "
from decimal import Decimal, ROUND_DOWN
import sys
d = Decimal(sys.argv[1].strip())
if d <= 0:
    sys.exit('troy_ounces must be positive')
# 1 troy oz = 10^6 base units (6 decimals)
b = (d * Decimal(10**6)).to_integral_value(rounding=ROUND_DOWN)
if b <= 0 or b > 2**256 - 1:
    sys.exit('amount out of range')
print(int(b))
" "$OZ")" || exit 1

if [ -n "${MINT_TO:-}" ]; then
  TO="$MINT_TO"
else
  TO="$(cast wallet address "$PRIVATE_KEY")" || exit 1
fi

echo "=== Mint XAU-compliant tokens (troy oz) ==="
echo "  RPC: $RPC"
echo "  Recipient: $TO"
echo "  Troy ounces: $OZ  ->  base units: $BASE_UNITS"
echo "  cXAUC: $DO_CXAUC  cXAUT: $DO_CXAUT"
echo ""

MULTISIG="${ADDR_MULTISIG:-0xb9E29cFa1f89d369671E640d0BB3aD94Cab43965}"
GAS_LIMIT_MULTISIG="${GAS_LIMIT_MULTISIG:-600000}"
GAS_PRICE="${GAS_PRICE_138:-1000000000}"

extract_tx_hash() {
  awk '/^transactionHash[[:space:]]/ {print $2; exit}'
}

tx_status_ok() {
  local txhash="$1"
  [[ -n "$txhash" && "$txhash" == 0x* ]] || return 1
  local st
  st=$(cast receipt "$txhash" status --rpc-url "$RPC" 2>/dev/null | awk '{print $1}' || echo "")
  [[ "$st" == "1" || "$st" == "true" ]]
}

mint_via_multisig() {
  local addr="$1" label="$2"
  local data txid exec_out txhash count
  data=$(cast calldata "mint(address,uint256)" "$TO" "$BASE_UNITS")
  echo -n "  multisig mint $label... "
  if [ -n "${DRY_RUN:-}" ]; then
    echo "[dry-run]"
    return 0
  fi
  cast send "$MULTISIG" \
    "submitTransaction(address,uint256,bytes)" "$addr" 0 "$data" \
    --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy \
    --gas-limit "$GAS_LIMIT_MULTISIG" --gas-price "$GAS_PRICE" >/dev/null || {
    echo "FAIL (submit)"; return 1
  }
  count=$(cast call "$MULTISIG" "getTransactionCount()(uint256)" --rpc-url "$RPC" | awk '{print $1}')
  txid=$((count - 1))
  exec_out=$(cast send "$MULTISIG" "executeTransaction(uint256)" "$txid" \
    --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy \
    --gas-limit "$GAS_LIMIT_MULTISIG" --gas-price "$GAS_PRICE" 2>&1) || {
    echo "FAIL (execute)"; return 1
  }
  txhash=$(echo "$exec_out" | extract_tx_hash)
  if tx_status_ok "$txhash"; then
    echo "OK (tx $txhash)"
    return 0
  fi
  echo "FAIL (receipt: $txhash)"
  return 1
}

run_mint() {
  local addr="$1"
  local label="$2"
  local owner lc_to lc_own lc_ms
  owner=$(cast call "$addr" "owner()(address)" --rpc-url "$RPC" 2>/dev/null || echo "")
  lc_to=$(echo "$TO" | tr '[:upper:]' '[:lower:]')
  lc_own=$(echo "$owner" | tr '[:upper:]' '[:lower:]')
  lc_ms=$(echo "$MULTISIG" | tr '[:upper:]' '[:lower:]')
  if [[ "$lc_own" == "$lc_ms" ]]; then
    mint_via_multisig "$addr" "$label" || return 1
    return 0
  fi
  if [ -n "${DRY_RUN:-}" ]; then
    echo "[dry-run] cast send $label $addr mint $TO $BASE_UNITS"
    return 0
  fi
  cast send "$addr" "mint(address,uint256)" "$TO" "$BASE_UNITS" \
    --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy --gas-limit "$GAS_LIMIT"
}

[ "$DO_CXAUC" = 1 ] && run_mint "$CXAUC" "cXAUC"
[ "$DO_CXAUT" = 1 ] && run_mint "$CXAUT" "cXAUT"
echo "Done."
