#!/usr/bin/env bash
# Check and fix bridge allowance
# Usage: ./check-and-fix-allowance.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE_PROJECT="/home/intlc/projects/smom-dbis-138"

source "$SOURCE_PROJECT/.env"

RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
WETH9_ADDRESS="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
BRIDGE_ADDRESS="0x89dd12025bfCD38A168455A44B400e913ED33BE2"

DEPLOYER=$(cast wallet address --private-key "$PRIVATE_KEY" 2>/dev/null)
AMOUNT_WEI=$(cast --to-wei 6.0 ether)

echo "=== Checking Bridge Allowance ==="
echo "Deployer: $DEPLOYER"
echo "Bridge: $BRIDGE_ADDRESS"
echo ""

# Check current allowance
ALLOW=$(cast call "$WETH9_ADDRESS" "allowance(address,address)" "$DEPLOYER" "$BRIDGE_ADDRESS" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")

if [ "$ALLOW" != "0" ] && [ "$ALLOW" != "0x0000000000000000000000000000000000000000000000000000000000000000" ]; then
    ALLOW_ETH=$(echo "scale=6; $ALLOW / 1000000000000000000" | bc 2>/dev/null || echo "0")
    echo "✅ Allowance exists: $ALLOW_ETH ETH"
    exit 0
fi

echo "⚠️  Allowance is 0. Attempting to approve..."
echo ""

# Get current nonce
CURRENT_NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
echo "Current nonce: $CURRENT_NONCE"

# Try to approve
echo "Sending approval transaction..."
TX_OUTPUT=$(cast send "$WETH9_ADDRESS" \
    "approve(address,uint256)" \
    "$BRIDGE_ADDRESS" \
    "$AMOUNT_WEI" \
    --rpc-url "$RPC_URL" \
    --private-key "$PRIVATE_KEY" \
    --gas-price 20000000000 \
    --nonce "$CURRENT_NONCE" \
    2>&1 || echo "FAILED")

if echo "$TX_OUTPUT" | grep -qE "transactionHash"; then
    HASH=$(echo "$TX_OUTPUT" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}')
    echo "✅ Transaction sent: $HASH"
    echo ""
    echo "Waiting 30 seconds for confirmation..."
    sleep 30
    
    # Check again
    ALLOW=$(cast call "$WETH9_ADDRESS" "allowance(address,address)" "$DEPLOYER" "$BRIDGE_ADDRESS" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    if [ "$ALLOW" != "0" ] && [ "$ALLOW" != "0x0000000000000000000000000000000000000000000000000000000000000000" ]; then
        ALLOW_ETH=$(echo "scale=6; $ALLOW / 1000000000000000000" | bc 2>/dev/null || echo "0")
        echo "✅ Allowance confirmed: $ALLOW_ETH ETH"
        exit 0
    else
        echo "⚠️  Allowance still pending. Transaction may need more time to be mined."
        echo "Transaction hash: $HASH"
        exit 1
    fi
else
    ERR=$(echo "$TX_OUTPUT" | grep -E "Error|Known|underpriced" | head -1 || echo "Unknown error")
    echo "❌ Approval failed: $ERR"
    echo ""
    echo "Full output:"
    echo "$TX_OUTPUT" | tail -5
    exit 1
fi

