#!/usr/bin/env bash
# Implement key recommendations for bridge system
# Usage: ./implement-recommendations.sh [recommendation_number]

set -euo pipefail

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

# 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"; }

source "$SOURCE_PROJECT/.env" 2>/dev/null || true

log_info "========================================="
log_info "Implement Key Recommendations"
log_info "========================================="
log_info ""

# Recommendation 1: Dynamic Gas Pricing
implement_dynamic_gas() {
    log_info "1. Implementing Dynamic Gas Pricing..."
    
    RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
    CURRENT_GAS=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "1000000000")
    MULTIPLIER=1.5
    OPTIMAL_GAS=$(echo "scale=0; $CURRENT_GAS * $MULTIPLIER / 1" | bc)
    
    log_success "✓ Current gas: $(echo "scale=2; $CURRENT_GAS / 1000000000" | bc) gwei"
    log_success "✓ Optimal gas: $(echo "scale=2; $OPTIMAL_GAS / 1000000000" | bc) gwei"
    log_info "  Use this gas price for faster transaction inclusion"
}

# Recommendation 2: Bridge Status Check
implement_status_check() {
    log_info "2. Creating Bridge Status Check Script..."
    
    cat > "$SCRIPT_DIR/check-bridge-status.sh" <<'EOF'
#!/usr/bin/env bash
# Quick bridge status check
source /home/intlc/projects/smom-dbis-138/.env
RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
DEPLOYER=$(cast wallet address --private-key "$PRIVATE_KEY" 2>/dev/null)

echo "=== Bridge Status ==="
echo "WETH9 Allowance: $(cast call 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 'allowance(address,address)' $DEPLOYER 0x89dd12025bfCD38A168455A44B400e913ED33BE2 --rpc-url $RPC_URL)"
echo "WETH10 Allowance: $(cast call 0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f 'allowance(address,address)' $DEPLOYER 0xe0E93247376aa097dB308B92e6Ba36bA015535D0 --rpc-url $RPC_URL)"
EOF
    
    chmod +x "$SCRIPT_DIR/check-bridge-status.sh"
    log_success "✓ Created check-bridge-status.sh"
}

# Recommendation 3: Enhanced Error Handling
implement_error_handling() {
    log_info "3. Creating Error Handling Utilities..."
    
    cat > "$SCRIPT_DIR/lib/error-handling.sh" <<'EOF'
#!/usr/bin/env bash
# Error handling utilities

handle_rpc_error() {
    local error="$1"
    if echo "$error" | grep -q "insufficient funds"; then
        echo "ERROR: Insufficient balance for transaction"
        return 1
    elif echo "$error" | grep -q "nonce too low"; then
        echo "ERROR: Transaction nonce too low. Wait for pending transactions."
        return 1
    elif echo "$error" | grep -q "replacement transaction underpriced"; then
        echo "ERROR: Pending transaction exists. Wait or increase gas price."
        return 1
    elif echo "$error" | grep -q "execution reverted"; then
        echo "ERROR: Transaction reverted. Check contract state."
        return 1
    fi
    return 0
}

retry_transaction() {
    local command="$1"
    local max_retries=3
    local retry=0
    
    while [ $retry -lt $max_retries ]; do
        if eval "$command"; then
            return 0
        fi
        ((retry++))
        sleep 5
    done
    return 1
}
EOF
    
    chmod +x "$SCRIPT_DIR/lib/error-handling.sh"
    log_success "✓ Created error-handling utilities"
}

# Recommendation 4: Transaction Logging
implement_transaction_logging() {
    log_info "4. Implementing Transaction Logging..."
    
    mkdir -p "$PROJECT_ROOT/logs"
    
    cat > "$SCRIPT_DIR/lib/transaction-logger.sh" <<'EOF'
#!/usr/bin/env bash
# Transaction logging utilities

LOG_DIR="${LOG_DIR:-/home/intlc/projects/proxmox/logs}"
LOG_FILE="$LOG_DIR/bridge-transactions-$(date +%Y%m%d).log"

log_transaction() {
    local tx_hash="$1"
    local chain="$2"
    local amount="$3"
    local status="$4"
    
    echo "[$(date -u +"%Y-%m-%d %H:%M:%S UTC")] $status | $chain | $amount | $tx_hash" >> "$LOG_FILE"
}

get_transaction_status() {
    local tx_hash="$1"
    local rpc_url="$2"
    cast tx "$tx_hash" --rpc-url "$rpc_url" 2>/dev/null | grep -E "status|blockNumber" || echo "Pending"
}
EOF
    
    chmod +x "$SCRIPT_DIR/lib/transaction-logger.sh"
    log_success "✓ Created transaction logging system"
}

# Recommendation 5: Health Check Script
implement_health_check() {
    log_info "5. Creating Health Check Script..."
    
    cat > "$SCRIPT_DIR/health-check.sh" <<'EOF'
#!/usr/bin/env bash
# Comprehensive health check for bridge system

source /home/intlc/projects/smom-dbis-138/.env
RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"

echo "=== Bridge System Health Check ==="
echo ""

# Check RPC connectivity
echo "1. RPC Connectivity:"
if cast block-number --rpc-url "$RPC_URL" >/dev/null 2>&1; then
    echo "  ✅ RPC is accessible"
else
    echo "  ❌ RPC is not accessible"
fi

# Check bridge contracts
echo ""
echo "2. Bridge Contracts:"
WETH9_BRIDGE="0x89dd12025bfCD38A168455A44B400e913ED33BE2"
WETH10_BRIDGE="0xe0E93247376aa097dB308B92e6Ba36bA015535D0"

if cast code "$WETH9_BRIDGE" --rpc-url "$RPC_URL" >/dev/null 2>&1; then
    echo "  ✅ WETH9 Bridge deployed"
else
    echo "  ❌ WETH9 Bridge not found"
fi

if cast code "$WETH10_BRIDGE" --rpc-url "$RPC_URL" >/dev/null 2>&1; then
    echo "  ✅ WETH10 Bridge deployed"
else
    echo "  ❌ WETH10 Bridge not found"
fi

# Check destination chains
echo ""
echo "3. Destination Chains:"
declare -A CHAINS=(
    ["BSC"]="11344663589394136015"
    ["Polygon"]="4051577828743386545"
    ["Avalanche"]="6433500567565415381"
    ["Base"]="15971525489660198786"
    ["Arbitrum"]="4949039107694359620"
    ["Optimism"]="3734403246176062136"
    ["Ethereum"]="5009297550715157269"
)

for chain in "${!CHAINS[@]}"; do
    selector="${CHAINS[$chain]}"
    result=$(cast call "$WETH9_BRIDGE" "destinations(uint64)" "$selector" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    if [ -n "$result" ] && ! echo "$result" | grep -q "0x0000000000000000000000000000000000000000$"; then
        echo "  ✅ $chain configured"
    else
        echo "  ❌ $chain not configured"
    fi
done
EOF
    
    chmod +x "$SCRIPT_DIR/health-check.sh"
    log_success "✓ Created health-check.sh"
}

# Main execution
RECOMMENDATION="${1:-all}"

case "$RECOMMENDATION" in
    1) implement_dynamic_gas ;;
    2) implement_status_check ;;
    3) implement_error_handling ;;
    4) implement_transaction_logging ;;
    5) implement_health_check ;;
    all)
        implement_dynamic_gas
        implement_status_check
        implement_error_handling
        implement_transaction_logging
        implement_health_check
        ;;
    *)
        log_error "Unknown recommendation: $RECOMMENDATION"
        exit 1
        ;;
esac

log_info ""
log_success "========================================="
log_success "Recommendations Implemented!"
log_success "========================================="

