#!/usr/bin/env bash
# Mint tokens to reach 750 million total supply
# Usage: ./mint-to-750m.sh [usdt|usdc|both] [recipient_address]

set -euo pipefail

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

if [[ -f "$SCRIPT_DIR/lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "$PROJECT_ROOT"
elif [ -f "$PROJECT_ROOT/.env" ]; then
    set -a && source "$PROJECT_ROOT/.env" && set +a
fi

RPC_URL="${RPC_URL:-${RPC_URL_138:-http://192.168.11.211:8545}}"
RPC_URL="${RPC_URL%$'\r'}"
RPC_URL="${RPC_URL%$'\n'}"
USDT_ADDRESS="0x93E66202A11B1772E55407B32B44e5Cd8eda7f22"
USDC_ADDRESS="0xf22258f57794CC8E06237084b353Ab30fFfa640b"

# Amount to mint: 749 million tokens = 749,000,000,000,000 base units (6 decimals)
AMOUNT_TO_MINT="749000000000000"
TARGET_TOTAL="750000000000000"  # 750 million in base units

TOKEN="${1:-both}"
RECIPIENT="${2:-}"

if [ -z "$RECIPIENT" ]; then
    echo "Error: Recipient address required"
    echo "Usage: $0 [usdt|usdc|both] <recipient_address>"
    exit 1
fi

if [ -z "${PRIVATE_KEY:-}" ]; then
    echo "Error: PRIVATE_KEY not set in environment"
    echo "Please set PRIVATE_KEY in .env file or export it"
    exit 1
fi

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }

mint_tokens() {
    local token_address=$1
    local token_name=$2
    local amount=$3
    local recipient=$4
    
    log_info "Minting $token_name..."
    log_info "  Contract: $token_address"
    log_info "  Recipient: $recipient"
    log_info "  Amount: $amount base units (749,000,000 tokens)"
    
    # Check current supply
    CURRENT_SUPPLY=$(cast call "$token_address" "totalSupply()" --rpc-url "$RPC_URL" 2>/dev/null | cast --to-dec 2>/dev/null || echo "0")
    CURRENT_TOKENS=$(echo "scale=6; $CURRENT_SUPPLY / 1000000" | bc 2>/dev/null || echo "0")
    log_info "  Current Total Supply: $CURRENT_TOKENS tokens ($CURRENT_SUPPLY base units)"
    
    # Verify owner
    OWNER_RAW=$(cast call "$token_address" "owner()" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    # Extract address from padded hex (address is last 20 bytes = 40 hex chars)
    if echo "$OWNER_RAW" | grep -q "^0x"; then
        # Get last 40 characters (20 bytes) and prepend 0x
        OWNER="0x$(echo "$OWNER_RAW" | sed 's/^0x//' | tail -c 41 | tr -d '\n')"
    else
        OWNER="$OWNER_RAW"
    fi
    SENDER_ADDR=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || echo "")
    
    log_info "  Contract Owner: $OWNER"
    log_info "  Transaction Sender: $SENDER_ADDR"
    
    # Normalize addresses for comparison (lowercase)
    OWNER_LOWER=$(echo "$OWNER" | tr '[:upper:]' '[:lower:]')
    SENDER_LOWER=$(echo "$SENDER_ADDR" | tr '[:upper:]' '[:lower:]')
    
    if [ -z "$OWNER" ] || [ "$OWNER_LOWER" != "$SENDER_LOWER" ]; then
        log_warn "  Warning: Private key address ($SENDER_ADDR) does not match the owner ($OWNER)"
        log_error "  Cannot mint: Only the contract owner can mint tokens"
        return 1
    fi
    
    # Send mint transaction
    log_info "  Sending transaction..."
    cast send "$token_address" \
      "mint(address,uint256)" \
      "$recipient" \
      "$amount" \
      --rpc-url "$RPC_URL" \
      --private-key "$PRIVATE_KEY" \
      --gas-price 20000000000 \
      --legacy \
      -vv
    
    if [ $? -eq 0 ]; then
        log_success "  Mint transaction sent successfully"
        
        # Wait a moment for block confirmation
        sleep 3
        
        # Check new supply
        NEW_SUPPLY=$(cast call "$token_address" "totalSupply()" --rpc-url "$RPC_URL" 2>/dev/null | cast --to-dec 2>/dev/null || echo "0")
        NEW_TOKENS=$(echo "scale=6; $NEW_SUPPLY / 1000000" | bc 2>/dev/null || echo "0")
        log_info "  New Total Supply: $NEW_TOKENS tokens ($NEW_SUPPLY base units)"
        
        if [ "$NEW_TOKENS" = "750000000.000000" ] || [ "$NEW_TOKENS" = "750000000" ]; then
            log_success "  ✅ Successfully minted to 750 million tokens!"
        else
            log_warn "  ⚠️  Total supply is $NEW_TOKENS, expected 750000000"
        fi
    else
        log_error "  Mint transaction failed"
        return 1
    fi
}

log_info "========================================="
log_info "Mint Tokens to 750 Million Total Supply"
log_info "========================================="
log_info ""

if [ "$TOKEN" = "usdt" ] || [ "$TOKEN" = "both" ]; then
    mint_tokens "$USDT_ADDRESS" "USDT" "$AMOUNT_TO_MINT" "$RECIPIENT"
    log_info ""
fi

if [ "$TOKEN" = "usdc" ] || [ "$TOKEN" = "both" ]; then
    mint_tokens "$USDC_ADDRESS" "USDC" "$AMOUNT_TO_MINT" "$RECIPIENT"
    log_info ""
fi

log_info "========================================="
log_info "Verification"
log_info "========================================="
log_info ""

# Verify final supplies
if [ "$TOKEN" = "usdt" ] || [ "$TOKEN" = "both" ]; then
    FINAL_USDT=$(cast call "$USDT_ADDRESS" "totalSupply()" --rpc-url "$RPC_URL" 2>/dev/null | cast --to-dec 2>/dev/null || echo "0")
    FINAL_USDT_TOKENS=$(echo "scale=6; $FINAL_USDT / 1000000" | bc 2>/dev/null || echo "0")
    log_success "USDT Final Total Supply: $FINAL_USDT_TOKENS tokens"
fi

if [ "$TOKEN" = "usdc" ] || [ "$TOKEN" = "both" ]; then
    FINAL_USDC=$(cast call "$USDC_ADDRESS" "totalSupply()" --rpc-url "$RPC_URL" 2>/dev/null | cast --to-dec 2>/dev/null || echo "0")
    FINAL_USDC_TOKENS=$(echo "scale=6; $FINAL_USDC / 1000000" | bc 2>/dev/null || echo "0")
    log_success "USDC Final Total Supply: $FINAL_USDC_TOKENS tokens"
fi

