#!/usr/bin/env bash
# Wrap ETH to WETH9 and Bridge to Ethereum Mainnet (Chain 138 → Ethereum Mainnet via CCIP)
# Usage: ./wrap-and-bridge-weth9-to-mainnet.sh <amount_in_eth> [recipient_address] [private_key]
# Env: PRIVATE_KEY (or 3rd arg), RPC_URL or RPC_URL_138, CCIPWETH9_BRIDGE_CHAIN138.
#      Optional: WETH9_ADDRESS_CHAIN138 (if Chain 138 uses different WETH9), EXPLORER_URL_138.

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}[⚠]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }

if [[ -f "$SCRIPT_DIR/lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "$PROJECT_ROOT"
elif [ -f "$PROJECT_ROOT/.env" ]; then
    set -a && source "$PROJECT_ROOT/.env" && set +a
fi

# Configuration (override WETH9_ADDRESS / WETH9_ADDRESS_CHAIN138 if Chain 138 uses a different WETH9)
RPC_URL="${RPC_URL:-${RPC_URL_138:-http://192.168.11.211:8545}}"
RPC_URL="${RPC_URL%$'\r'}"
RPC_URL="${RPC_URL%$'\n'}"
WETH9_ADDRESS="${WETH9_ADDRESS_CHAIN138:-${WETH9_ADDRESS:-0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2}}"
WETH9_BRIDGE="${CCIPWETH9_BRIDGE_CHAIN138:-0x971cD9D156f193df8051E48043C476e53ECd4693}"
EXPLORER_URL_138="${EXPLORER_URL_138:-https://explorer.d-bis.org}"
ETHEREUM_SELECTOR="5009297550715157269"
LINK_TOKEN="${LINK_TOKEN:-0x514910771AF9Ca656af840dff83E8264EcF986CA}"

# Parse arguments
AMOUNT_ETH="${1:-}"
RECIPIENT="${2:-}"
PRIVATE_KEY="${3:-${PRIVATE_KEY:-}}"

if [ -z "$AMOUNT_ETH" ]; then
    log_error "Amount in ETH required"
    echo "Usage: $0 <amount_in_eth> [recipient_address] [private_key]"
    echo "Example: $0 20000 0xYourAddress 0xYourPrivateKey"
    exit 1
fi

if [ -z "$PRIVATE_KEY" ]; then
    log_error "PRIVATE_KEY not set. Please provide as argument or set in .env"
    exit 1
fi

# Get sender address
SENDER=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || echo "")
if [ -z "$SENDER" ]; then
    log_error "Failed to derive address from private key"
    exit 1
fi

# Use sender as recipient if not provided
if [ -z "$RECIPIENT" ]; then
    RECIPIENT="$SENDER"
    log_info "Recipient not provided, using sender address: $RECIPIENT"
fi

# Convert amount to wei
AMOUNT_WEI=$(cast --to-wei "$AMOUNT_ETH" ether 2>/dev/null || echo "")
if [ -z "$AMOUNT_WEI" ]; then
    log_error "Failed to convert amount to wei"
    exit 1
fi

log_info "========================================="
log_info "Wrap ETH to WETH9 and Bridge to Mainnet"
log_info "========================================="
log_info ""
log_info "Amount: $AMOUNT_ETH ETH"
log_info "Amount (wei): $AMOUNT_WEI"
log_info "Sender: $SENDER"
log_info "Recipient (Mainnet): $RECIPIENT"
log_info "WETH9 Contract: $WETH9_ADDRESS"
log_info "Bridge Contract: $WETH9_BRIDGE"
log_info "Ethereum Mainnet Selector: $ETHEREUM_SELECTOR"
log_info "RPC URL: $RPC_URL"
log_info ""

# Safety check for large amounts
AMOUNT_NUM=$(echo "$AMOUNT_ETH" | bc 2>/dev/null || echo "0")
if (( $(echo "$AMOUNT_NUM > 1000" | bc -l 2>/dev/null || echo 0) )); then
    log_warn "⚠️  Large amount detected: $AMOUNT_ETH ETH"
    log_warn "This is a significant transaction. Please verify all details carefully."
    read -p "Continue? (yes/no): " -r
    echo
    if [[ ! $REPLY =~ ^[Yy][Ee][Ss]$ ]]; then
        log_info "Transaction cancelled"
        exit 0
    fi
fi

# Check ETH balance
log_info "Checking ETH balance..."
ETH_BALANCE=$(cast balance "$SENDER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
ETH_BALANCE_ETH=$(echo "scale=6; $ETH_BALANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")
log_info "ETH Balance: $ETH_BALANCE_ETH ETH ($ETH_BALANCE wei)"

if (( $(echo "$ETH_BALANCE < $AMOUNT_WEI" | bc -l 2>/dev/null || echo 1) )); then
    log_error "Insufficient ETH balance. Need $AMOUNT_ETH ETH, have $ETH_BALANCE_ETH ETH"
    exit 1
fi

# Check WETH9 balance (cast returns hex; parse to decimal for bc)
log_info "Checking WETH9 balance..."
WETH9_BALANCE_RAW=$(cast call "$WETH9_ADDRESS" "balanceOf(address)(uint256)" "$SENDER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
WETH9_BALANCE=$(echo "$WETH9_BALANCE_RAW" | tr -d '\n\r' | sed 's/\[.*//' | grep -oE '^[0-9]+$' || echo "$WETH9_BALANCE_RAW" | cast --to-dec 2>/dev/null || echo "0")
[[ -z "$WETH9_BALANCE" ]] && WETH9_BALANCE=0
WETH9_BALANCE_ETH=$(echo "scale=6; $WETH9_BALANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")
log_info "WETH9 Balance: $WETH9_BALANCE_ETH WETH9 ($WETH9_BALANCE wei)"

# Step 1: Wrap ETH to WETH9 (if needed)
NEED_TO_WRAP=false
if (( $(echo "${WETH9_BALANCE:-0} < $AMOUNT_WEI" | bc -l 2>/dev/null || echo 1) )); then
    NEED_TO_WRAP=true
    WRAP_AMOUNT=$(echo "$AMOUNT_WEI - ${WETH9_BALANCE:-0}" | bc 2>/dev/null || echo "$AMOUNT_WEI")
    [[ -z "$WRAP_AMOUNT" ]] || [[ "$WRAP_AMOUNT" -lt "$AMOUNT_WEI" ]] 2>/dev/null && WRAP_AMOUNT="$AMOUNT_WEI"
    WRAP_AMOUNT_ETH=$(echo "scale=6; $WRAP_AMOUNT / 1000000000000000000" | bc 2>/dev/null || echo "0")
    
    log_info ""
    log_info "Step 1: Wrapping ETH to WETH9..."
    log_info "  Amount to wrap: $WRAP_AMOUNT_ETH ETH (wei: $WRAP_AMOUNT)"
    
    # Check if we have enough ETH for wrapping
    if (( $(echo "$ETH_BALANCE < $WRAP_AMOUNT" | bc -l 2>/dev/null || echo 1) )); then
        log_error "Insufficient ETH to wrap. Need $WRAP_AMOUNT_ETH ETH"
        exit 1
    fi
    
    [[ -z "$WRAP_AMOUNT" ]] && WRAP_AMOUNT="$AMOUNT_WEI"
    [[ "$WRAP_AMOUNT" = "0" ]] && WRAP_AMOUNT="$AMOUNT_WEI"
    log_info "  Sending transaction (value=$WRAP_AMOUNT wei)..."
    WRAP_TX=$(cast send "$WETH9_ADDRESS" \
        "deposit()" \
        --value "$WRAP_AMOUNT" \
        --rpc-url "$RPC_URL" \
        --private-key "$PRIVATE_KEY" \
        --gas-price "${GAS_PRICE_138:-1000000000}" \
        --gas-limit "${GAS_LIMIT_138:-200000}" \
        --legacy \
        -vv 2>&1 || echo "")
    
    if echo "$WRAP_TX" | grep -qE "transactionHash"; then
        TX_HASH=$(echo "$WRAP_TX" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}' || echo "")
        log_success "✓ Wrap transaction sent: $TX_HASH"
        log_info "Waiting for confirmation (15 seconds)..."
        sleep 15
        
        # Verify WETH9 balance (same parsing as initial balance: balanceOf returns uint256)
        NEW_WETH9_RAW=$(cast call "$WETH9_ADDRESS" "balanceOf(address)(uint256)" "$SENDER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
        NEW_WETH9_BALANCE=$(echo "$NEW_WETH9_RAW" | tr -d '\n\r' | sed 's/\[.*//' | grep -oE '^[0-9]+$' || echo "$NEW_WETH9_RAW" | cast --to-dec 2>/dev/null || echo "0")
        [[ -z "$NEW_WETH9_BALANCE" ]] && NEW_WETH9_BALANCE=0
        NEW_WETH9_BALANCE_ETH=$(echo "scale=6; $NEW_WETH9_BALANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")
        log_success "✓ New WETH9 Balance: $NEW_WETH9_BALANCE_ETH WETH9"
        if (( $(echo "${NEW_WETH9_BALANCE:-0} < $WRAP_AMOUNT" | bc -l 2>/dev/null || echo 1) )); then
            log_error "WETH9 balance did not increase after wrap (got $NEW_WETH9_BALANCE_ETH WETH9). Wrap tx may have reverted."
            log_info "Check wrap tx on explorer: $EXPLORER_URL_138/tx/$TX_HASH"
            log_info "If the tx reverted, fix the cause (e.g. wrong WETH9 address on this chain) before re-running."
            exit 1
        fi
    else
        log_error "Failed to wrap ETH"
        log_info "Output: $WRAP_TX"
        exit 1
    fi
else
    log_success "✓ WETH9 balance sufficient ($WETH9_BALANCE_ETH WETH9)"
fi

# Step 2: Approve bridge (if needed)
log_info ""
log_info "Step 2: Checking bridge approval..."
ALLOWANCE_RAW=$(cast call "$WETH9_ADDRESS" "allowance(address,address)(uint256)" "$SENDER" "$WETH9_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
ALLOWANCE=$(echo "$ALLOWANCE_RAW" | tr -d '\n\r' | grep -oE '^[0-9]+$' || echo "$ALLOWANCE_RAW" | cast --to-dec 2>/dev/null || echo "0")
[[ -z "$ALLOWANCE" ]] && ALLOWANCE=0

if (( $(echo "$ALLOWANCE < $AMOUNT_WEI" | bc -l 2>/dev/null || echo 1) )); then
    log_info "Approving bridge to spend WETH9..."
    MAX_UINT256="115792089237316195423570985008687907853269984665640564039457584007913129639935"
    
    APPROVE_TX=$(cast send "$WETH9_ADDRESS" \
        "approve(address,uint256)" \
        "$WETH9_BRIDGE" \
        "$MAX_UINT256" \
        --rpc-url "$RPC_URL" \
        --private-key "$PRIVATE_KEY" \
        --gas-price "${GAS_PRICE_138:-1000000000}" \
        --gas-limit "${GAS_LIMIT_138:-200000}" \
        --legacy \
        -vv 2>&1 || echo "")
    
    if echo "$APPROVE_TX" | grep -qE "transactionHash"; then
        TX_HASH=$(echo "$APPROVE_TX" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}' || echo "")
        log_success "✓ Approval transaction sent: $TX_HASH"
        log_info "Waiting for confirmation (10 seconds)..."
        sleep 10
    else
        log_error "Failed to approve bridge"
        log_info "Output: $APPROVE_TX"
        exit 1
    fi
else
    ALLOWANCE_ETH=$(echo "scale=6; $ALLOWANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")
    log_success "✓ Bridge already approved (Allowance: $ALLOWANCE_ETH WETH9)"
fi

# Step 3: Check LINK balance for fees
log_info ""
log_info "Step 3: Checking LINK balance for CCIP fees..."
LINK_BALANCE=$(cast call "$LINK_TOKEN" "balanceOf(address)" "$SENDER" --rpc-url "$RPC_URL" 2>/dev/null | cast --to-dec 2>/dev/null || echo "0")
LINK_BALANCE_ETH=$(echo "scale=6; $LINK_BALANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")
log_info "LINK Balance: $LINK_BALANCE_ETH LINK ($LINK_BALANCE wei)"

# Note: Fee estimation would require calling the router, which is complex
# For large amounts, fees are typically 0.1-1 LINK
if (( $(echo "$LINK_BALANCE < 1000000000000000000" | bc -l 2>/dev/null || echo 0) )); then
    log_warn "⚠️  Low LINK balance. You may need LINK tokens to pay CCIP fees."
    log_warn "Recommended: At least 1-2 LINK for large transfers"
fi

# Chain 138 LINK - approve for CCIP fees (bridge or router pulls). Canonical on 138: 0xb7721dD53A8c629d9f1Ba31a5819AFe250002b03 (see CHAIN138_TOKEN_ADDRESSES.md, LINK_TOKEN_STATUS_FINAL.md).
LINK_TOKEN_138="${LINK_TOKEN_CHAIN138:-${LINK_TOKEN:-0xb7721dD53A8c629d9f1Ba31a5819AFe250002b03}}"
CCIP_ROUTER_138="${CCIP_ROUTER_ADDRESS:-0x42DAb7b888Dd382bD5Adcf9E038dBF1fD03b4817}"
MAX_UINT256="115792089237316195423570985008687907853269984665640564039457584007913129639935"
log_info "Approving LINK for CCIP fees (bridge + router)..."
cast send "$LINK_TOKEN_138" "approve(address,uint256)" "$WETH9_BRIDGE" "$MAX_UINT256" \
    --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" --gas-price "${GAS_PRICE_138:-1000000000}" --gas-limit "${GAS_LIMIT_138:-200000}" --legacy -q 2>/dev/null || true
cast send "$LINK_TOKEN_138" "approve(address,uint256)" "$CCIP_ROUTER_138" "$MAX_UINT256" \
    --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" --gas-price "${GAS_PRICE_138:-1000000000}" --gas-limit "${GAS_LIMIT_138:-200000}" --legacy -q 2>/dev/null || true

# Pre-bridge: confirm we have enough WETH9 (avoid bridging 0 or less)
FINAL_WETH9_RAW=$(cast call "$WETH9_ADDRESS" "balanceOf(address)(uint256)" "$SENDER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
FINAL_WETH9=$(echo "$FINAL_WETH9_RAW" | tr -d '\n\r' | grep -oE '^[0-9]+$' || echo "$FINAL_WETH9_RAW" | cast --to-dec 2>/dev/null || echo "0")
[[ -z "$FINAL_WETH9" ]] && FINAL_WETH9=0
if (( $(echo "${FINAL_WETH9:-0} < $AMOUNT_WEI" | bc -l 2>/dev/null || echo 1) )); then
    FINAL_ETH=$(echo "scale=6; $FINAL_WETH9 / 1000000000000000000" | bc 2>/dev/null || echo "0")
    log_error "Insufficient WETH9 balance to bridge. Have $FINAL_ETH WETH9, need $AMOUNT_ETH WETH9."
    log_info "Ensure wrap succeeded and balance is visible on-chain before re-running."
    exit 1
fi

# Step 4: Bridge to Ethereum Mainnet
log_info ""
log_info "Step 4: Bridging WETH9 to Ethereum Mainnet..."
log_info "  Amount: $AMOUNT_ETH WETH9"
log_info "  Recipient (on Mainnet): $RECIPIENT"
log_info "  Destination Chain Selector: $ETHEREUM_SELECTOR"

# Final confirmation for large amounts
if (( $(echo "$AMOUNT_NUM > 1000" | bc -l 2>/dev/null || echo 0) )); then
    log_warn "⚠️  FINAL CONFIRMATION"
    log_warn "Amount: $AMOUNT_ETH ETH"
    log_warn "Recipient: $RECIPIENT"
    log_warn "This will bridge WETH9 tokens to Ethereum Mainnet via CCIP"
    read -p "Proceed with bridge transaction? (yes/no): " -r
    echo
    if [[ ! $REPLY =~ ^[Yy][Ee][Ss]$ ]]; then
        log_info "Transaction cancelled"
        exit 0
    fi
fi

log_info "Sending bridge transaction..."
BRIDGE_TX=$(cast send "$WETH9_BRIDGE" \
    "sendCrossChain(uint64,address,uint256)" \
    "$ETHEREUM_SELECTOR" \
    "$RECIPIENT" \
    "$AMOUNT_WEI" \
    --rpc-url "$RPC_URL" \
    --private-key "$PRIVATE_KEY" \
    --gas-price "${GAS_PRICE_138:-1000000000}" \
    --gas-limit "${GAS_LIMIT_138:-300000}" \
    --legacy \
    -vv 2>&1 || echo "")

if echo "$BRIDGE_TX" | grep -qE "transactionHash"; then
    TX_HASH=$(echo "$BRIDGE_TX" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}' || echo "")
    
    # Try to extract message ID from logs
    MESSAGE_ID=$(echo "$BRIDGE_TX" | grep -oE "0x[0-9a-f]{64}" | head -2 | tail -1 || echo "")
    
    log_success ""
    log_success "========================================="
    log_success "✓ Bridge Transaction Sent Successfully!"
    log_success "========================================="
    log_success ""
    log_success "Transaction Hash: $TX_HASH"
    if [ -n "$MESSAGE_ID" ] && [ "$MESSAGE_ID" != "$TX_HASH" ]; then
        log_success "CCIP Message ID: $MESSAGE_ID"
    fi
    log_success "Amount: $AMOUNT_ETH WETH9"
    log_success "Recipient (Mainnet): $RECIPIENT"
    log_success ""
    log_info "Next Steps:"
    log_info "1. Wait for CCIP confirmation (typically 1-5 minutes)"
    log_info "2. Check transaction on Blockscout: $EXPLORER_URL_138/tx/$TX_HASH"
    log_info "3. Verify receipt on Ethereum Mainnet (Etherscan)"
    log_info "4. Your WETH9 tokens will appear at $RECIPIENT on Ethereum Mainnet"
    log_info ""
else
    log_error "Failed to send bridge transaction"
    log_info "Output: $BRIDGE_TX"
    exit 1
fi
