#!/usr/bin/env bash
# Monitor bridge allowance until it's fixed
# Usage: ./monitor-allowance.sh [max_wait_seconds]

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)
MAX_WAIT="${1:-300}"  # Default 5 minutes
CHECK_INTERVAL=10

echo "=== Monitoring Bridge Allowance ==="
echo "Deployer: $DEPLOYER"
echo "Max wait: $MAX_WAIT seconds"
echo "Check interval: $CHECK_INTERVAL seconds"
echo ""

ELAPSED=0
while [ $ELAPSED -lt $MAX_WAIT ]; do
    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 FIXED!"
        echo "Amount: $ALLOW_ETH ETH"
        echo "Time elapsed: $ELAPSED seconds"
        exit 0
    fi
    
    echo "[$ELAPSED/$MAX_WAIT] Allowance still 0... waiting..."
    sleep $CHECK_INTERVAL
    ELAPSED=$((ELAPSED + CHECK_INTERVAL))
done

echo "⚠️  Timeout reached. Allowance is still 0."
echo "The transaction may need more time or there may be a network issue."
exit 1

