#!/usr/bin/env bash
# Resolve Stuck Transaction
# Task 4: Resolve Stuck Transaction
# Usage: ./resolve-stuck-transaction.sh [address] [nonce]

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 .env exists
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}"
ADDRESS="${1:-}"
STUCK_NONCE="${2:-}"

log_info "========================================="
log_info "Resolve Stuck Transaction"
log_info "========================================="
log_info ""

if [ -z "$ADDRESS" ]; then
    if [ -n "${PRIVATE_KEY:-}" ]; then
        ADDRESS=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || echo "")
        if [ -z "$ADDRESS" ]; then
            log_error "Could not derive address from private key"
            exit 1
        fi
    else
        log_error "Address or PRIVATE_KEY required"
        log_info "Usage: $0 [address] [nonce]"
        log_info "   OR: Set PRIVATE_KEY in .env"
        exit 1
    fi
fi

log_info "Address: $ADDRESS"
log_info "RPC URL: $RPC_URL"
log_info ""

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

# If stuck nonce provided, check that specific nonce
if [ -n "$STUCK_NONCE" ]; then
    log_info ""
    log_info "Checking stuck transaction at nonce $STUCK_NONCE..."
    
    # Try to get transaction by nonce (this may not work on all RPCs)
    log_info "Attempting to check transaction status..."
    log_warn "Note: Transaction may still be in mempool"
    log_info ""
    log_info "Options to resolve:"
    log_info "  1. Wait for transaction to timeout (usually 1-2 hours)"
    log_info "  2. Replace transaction with higher gas price:"
    log_info "     cast send <contract> <function> \\"
    log_info "       --rpc-url $RPC_URL \\"
    log_info "       --private-key <key> \\"
    log_info "       --gas-price <higher_price> \\"
    log_info "       --nonce $STUCK_NONCE"
    log_info ""
    log_info "  3. Contact network administrator to clear mempool"
    log_info "  4. Use different account for configuration"
else
    # Check for pending transactions
    log_info ""
    log_info "Checking for pending transactions..."
    log_warn "Note: Checking pending transactions requires RPC support"
    log_info ""
    log_info "If you know the stuck nonce, provide it:"
    log_info "  $0 $ADDRESS <nonce>"
fi

# Check if we can proceed with next nonce
if [ -n "$CURRENT_NONCE" ]; then
    NEXT_NONCE=$((CURRENT_NONCE))
    log_info ""
    log_info "Next available nonce: $NEXT_NONCE"
    log_info ""
    log_info "To configure destinations with next nonce:"
    log_info "  ./scripts/configure-all-bridge-destinations.sh"
    log_info ""
    log_warn "⚠ Make sure stuck transaction is cleared first"
fi

log_info ""
log_info "========================================="
log_info "Resolution Summary"
log_info "========================================="
log_info ""
log_info "Current Status:"
log_info "  - Address: $ADDRESS"
log_info "  - Current Nonce: ${CURRENT_NONCE:-unknown}"
if [ -n "$STUCK_NONCE" ]; then
    log_info "  - Stuck Nonce: $STUCK_NONCE"
fi
log_info ""
log_info "Recommended Actions:"
log_info "  1. Wait for transaction timeout (1-2 hours)"
log_info "  2. Replace with higher gas price"
log_info "  3. Use different account"
log_info ""

