#!/bin/bash

# 🪙 TOKEN MINTING SCRIPT
# ═══════════════════════════════════════════════════════════════

echo "🪙 MINTING TOKENS TO DESTINATION"
echo "═══════════════════════════════════════════════════════════════"

# Configuration
MINT="AGxEfuo9e99QaRfEyMbptLuidqnLg6vDCT4of5NtUtwv"
DESTINATION_OWNER="4UFmCebEmzESoDTtHrmaftXj7YAsAH4HMios3yMWyVUT"  # This is likely the owner, not the token account
AUTHORITY_KEYPAIR="/Users/mgild/.config/solana/id.json"
AMOUNT="1000000000"  # 1 billion tokens
RPC_URL="https://api.devnet.solana.com"

echo "📋 Configuration:"
echo "   🏛️  Mint: $MINT"
echo "   🎯 Destination Owner: $DESTINATION_OWNER" 
echo "   🔑 Authority: $(solana-keygen pubkey $AUTHORITY_KEYPAIR)"
echo "   💰 Amount: $AMOUNT tokens"
echo "   🌐 RPC: devnet"
echo ""

# Step 1: Check if this is actually a token account or if we need to find/create the ATA
echo "📋 Step 1: Checking if destination is a token account..."
ACCOUNT_INFO=$(solana account $DESTINATION_OWNER --url devnet --output json 2>/dev/null)

if echo "$ACCOUNT_INFO" | jq -e '.account.owner == "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"' > /dev/null; then
    echo "   ✅ Destination is a token account"
    TOKEN_ACCOUNT="$DESTINATION_OWNER"
else
    echo "   ⚠️  Destination is NOT a token account (owned by $(echo "$ACCOUNT_INFO" | jq -r '.account.owner // "unknown"'))"
    echo "   💡 Treating as owner address - will find/create associated token account"
    
    # Calculate the associated token account
    echo ""
    echo "📋 Step 2: Finding Associated Token Account..."
    TOKEN_ACCOUNT=$(spl-token address --owner $DESTINATION_OWNER --token $MINT --url devnet 2>/dev/null || echo "")
    
    if [ -z "$TOKEN_ACCOUNT" ]; then
        echo "   ❌ Failed to calculate ATA. The destination might not be a valid owner address."
        echo "   💡 Please provide either:"
        echo "      - A valid token account address, OR"
        echo "      - A valid wallet/owner address"
        exit 1
    fi
    
    echo "   🎯 Associated Token Account: $TOKEN_ACCOUNT"
    
    # Check if ATA exists
    ATA_INFO=$(solana account $TOKEN_ACCOUNT --url devnet --output json 2>/dev/null)
    if [ $? -eq 0 ]; then
        echo "   ✅ Associated token account exists"
    else
        echo "   ⚠️  Associated token account does not exist"
        echo "   🔧 Creating associated token account..."
        
        spl-token create-account $MINT --owner $DESTINATION_OWNER --fee-payer $AUTHORITY_KEYPAIR --url devnet
        if [ $? -eq 0 ]; then
            echo "   ✅ Associated token account created successfully"
        else
            echo "   ❌ Failed to create associated token account"
            exit 1
        fi
    fi
fi

echo ""
echo "📋 Step 3: Verifying mint authority..."
MINT_INFO=$(spl-token account-info $MINT --url devnet)
echo "$MINT_INFO"

echo ""
echo "📋 Step 4: Minting tokens..."
echo "   📤 Minting $AMOUNT tokens to $TOKEN_ACCOUNT..."

# Use spl-token to mint
spl-token mint $MINT $AMOUNT $TOKEN_ACCOUNT --mint-authority $AUTHORITY_KEYPAIR --url devnet

if [ $? -eq 0 ]; then
    echo ""
    echo "   ✅ MINTING SUCCESSFUL!"
    echo "   🎉 Successfully minted $AMOUNT tokens!"
    echo ""
    
    echo "📋 Step 5: Verification..."
    echo "   📊 Updated token account balance:"
    spl-token balance $MINT --owner $DESTINATION_OWNER --url devnet 2>/dev/null || spl-token balance --address $TOKEN_ACCOUNT --url devnet
    
    echo ""
    echo "   📊 Updated mint info:"
    spl-token account-info $MINT --url devnet
    
else
    echo ""
    echo "   ❌ MINTING FAILED!"
    echo "   💡 Check the error above for details"
    exit 1
fi

echo ""
echo "🎉 TOKEN MINTING COMPLETE!"
echo "═══════════════════════════════════════════════════════════════"