#!/usr/bin/env bash
# Test bridge quote for (ChainID 138, WETH) → (ChainID 1, USDT)
# Tests thirdweb Bridge API and CCIP Bridge
# Usage: ./test-bridge-quote.sh

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'
CYAN='\033[0;36m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
log_section() { echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"; echo -e "${CYAN}$1${NC}"; echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}\n"; }

# Configuration
CHAIN138_ID=138
ETHEREUM_MAINNET_ID=1
WETH_CANONICAL="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
USDT_MAINNET="0xdAC17F958D2ee523a2206206994597C13D831ec7"
AMOUNT="1000000000000000000"  # 1 WETH

log_section "Bridge Quote Test: (ChainID 138, WETH) → (ChainID 1, USDT)"

log_info "Route Details:"
log_info "  From Chain: $CHAIN138_ID"
log_info "  From Token: WETH at $WETH_CANONICAL"
log_info "  To Chain: $ETHEREUM_MAINNET_ID (Ethereum Mainnet)"
log_info "  To Token: USDT at $USDT_MAINNET"
log_info "  Amount: 1 WETH ($AMOUNT wei)"
log_info ""

# Test 1: thirdweb Bridge API
log_section "Test 1: thirdweb Bridge API"

THIRDWEB_ENDPOINTS=(
    "https://api.thirdweb.com/v1/bridge/quote"
    "https://bridge.thirdweb.com/api/quote"
)

BRIDGE_QUOTE_FOUND=false

for endpoint in "${THIRDWEB_ENDPOINTS[@]}"; do
    log_info "Trying endpoint: $endpoint"
    
    QUOTE_PAYLOAD=$(cat <<EOF
{
    "fromChainId": $CHAIN138_ID,
    "toChainId": $ETHEREUM_MAINNET_ID,
    "fromTokenAddress": "$WETH_CANONICAL",
    "toTokenAddress": "$USDT_MAINNET",
    "amount": "$AMOUNT"
}
EOF
)
    
    QUOTE_RESPONSE=$(curl -s -X POST "$endpoint" \
        -H "Content-Type: application/json" \
        -d "$QUOTE_PAYLOAD" \
        --max-time 10 \
        2>&1 || echo "ERROR")
    
    if [[ "$QUOTE_RESPONSE" != *"ERROR"* ]] && [[ "$QUOTE_RESPONSE" != *"404"* ]]; then
        if command -v jq &> /dev/null; then
            # Check for valid quote
            if echo "$QUOTE_RESPONSE" | jq -e '.quoteId, .estimatedTime, .fee, .toAmount' >/dev/null 2>&1; then
                log_success "✅ Valid route found via thirdweb Bridge!"
                log_info "   Quote Response:"
                echo "$QUOTE_RESPONSE" | jq '.' 2>/dev/null || echo "$QUOTE_RESPONSE"
                BRIDGE_QUOTE_FOUND=true
                break
            elif echo "$QUOTE_RESPONSE" | jq -e '.error, .message' >/dev/null 2>&1; then
                ERROR_MSG=$(echo "$QUOTE_RESPONSE" | jq -r '.error // .message // "Unknown error"' 2>/dev/null || echo "API error")
                log_warn "   API returned error: $ERROR_MSG"
                log_info "   Full response: $QUOTE_RESPONSE"
            else
                log_warn "   Unexpected response format"
                log_info "   Response: $QUOTE_RESPONSE"
            fi
        else
            log_warn "   jq not available, cannot parse response"
            log_info "   Raw response: $QUOTE_RESPONSE"
        fi
    else
        log_warn "   Endpoint returned error or not found"
    fi
done

if [ "$BRIDGE_QUOTE_FOUND" = false ]; then
    log_warn "⚠ No valid route found via thirdweb Bridge API"
    log_info "   Possible reasons:"
    log_info "   1. ChainID 138 not supported by thirdweb Bridge"
    log_info "   2. WETH token not recognized at canonical address"
    log_info "   3. No liquidity for WETH → USDT route"
    log_info "   4. API requires authentication"
fi

# Test 2: CCIP Bridge (alternative)
log_section "Test 2: CCIP Bridge Alternative"

log_info "CCIP Bridge is available as alternative:"
log_info "  CCIPWETH9Bridge: 0x89dd12025bfCD38A168455A44B400e913ED33BE2"
log_info "  This bridge supports ChainID 138 and can bridge WETH"
log_info "  After bridging, swap WETH → USDT on Ethereum Mainnet"
log_info ""

# Summary
log_section "Bridge Quote Test Summary"

if [ "$BRIDGE_QUOTE_FOUND" = true ]; then
    log_success "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_success "✅ ROUTE EXISTS: Bridge quote obtained"
    log_success "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_info ""
    log_info "You can proceed with bridging WETH → USDT via thirdweb Bridge"
    log_info "Next steps:"
    log_info "  1. Implement approval flow"
    log_info "  2. Execute bridge transaction"
    log_info "  3. Monitor bridge status"
    exit 0
else
    log_warn "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_warn "⚠ NO DIRECT ROUTE: Bridge quote not available"
    log_warn "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_info ""
    log_info "Recommendation: Use CCIP Bridge instead"
    log_info "  Route: Bridge WETH via CCIP → Swap to USDT on Mainnet"
    log_info ""
    log_info "Or try alternative routes:"
    log_info "  1. Bridge to intermediate L2 (Arbitrum/Optimism/Base)"
    log_info "  2. Swap on L2, then bridge to mainnet"
    exit 1
fi
