#!/usr/bin/env bash
# Monitor Transactions for Stuck/Failed Status
# Usage: ./monitor-transactions.sh [tx_hash] [max_wait_seconds]

set -euo pipefail

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

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

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

# Load environment variables
if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"
elif [ -f "$PROJECT_ROOT/../.env" ]; then
    source "$PROJECT_ROOT/../.env"
fi

# Configuration
RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
TX_HASH="${1:-}"
MAX_WAIT="${2:-300}"  # Default 5 minutes
CHECK_INTERVAL=10

if [ -z "$TX_HASH" ]; then
    log_error "Transaction hash required"
    log_info "Usage: $0 <tx_hash> [max_wait_seconds]"
    exit 1
fi

log_info "========================================="
log_info "Transaction Monitor"
log_info "========================================="
log_info ""
log_info "Transaction: $TX_HASH"
log_info "Max Wait: $MAX_WAIT seconds"
log_info "Check Interval: $CHECK_INTERVAL seconds"
log_info ""

ELAPSED=0
while [ $ELAPSED -lt $MAX_WAIT ]; do
    # Get transaction receipt
    RECEIPT=$(cast receipt "$TX_HASH" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    
    if [ -n "$RECEIPT" ]; then
        # Check status
        STATUS=$(echo "$RECEIPT" | grep -oE "status[[:space:]]+[0-9]+" | awk '{print $2}' || echo "")
        BLOCK_NUMBER=$(echo "$RECEIPT" | grep -oE "blockNumber[[:space:]]+[0-9]+" | awk '{print $2}' || echo "")
        
        if [ "$STATUS" = "1" ]; then
            log_success "Transaction confirmed!"
            log_info "  Block: $BLOCK_NUMBER"
            log_info "  Status: Success"
            exit 0
        elif [ "$STATUS" = "0" ]; then
            log_error "Transaction reverted!"
            log_info "  Block: $BLOCK_NUMBER"
            log_info "  Status: Failed"
            
            # Try to get revert reason
            TX_DATA=$(cast tx "$TX_HASH" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
            if echo "$TX_DATA" | grep -qi "revert"; then
                REVERT_REASON=$(echo "$TX_DATA" | grep -i "revert" | head -1 || echo "")
                log_info "  Reason: $REVERT_REASON"
            fi
            exit 1
        fi
    else
        # Check if transaction exists in mempool
        TX_DATA=$(cast tx "$TX_HASH" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
        if [ -z "$TX_DATA" ]; then
            log_warn "Transaction not found (may have been dropped)"
            exit 1
        fi
    fi
    
    log_info "[$ELAPSED/$MAX_WAIT] Transaction pending... waiting..."
    sleep $CHECK_INTERVAL
    ELAPSED=$((ELAPSED + CHECK_INTERVAL))
done

log_warn "Timeout reached. Transaction still pending."
log_info "Transaction may be stuck. Consider:"
log_info "  1. Checking gas price"
log_info "  2. Replacing with higher gas price"
log_info "  3. Contacting network administrator"
exit 1

