#!/usr/bin/env bash
# Complete All Prerequisites for Bridge Funding
# This script orchestrates all prerequisite steps
# Usage: ./complete-prerequisites.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
source "$PROJECT_ROOT/scripts/lib/address-inventory.sh"

# 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_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
log_header() { echo -e "${CYAN}[HEADER]${NC} $1"; }

load_explorer_runtime_env

RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
LINK_TOKEN="$(resolve_address_value LINK_TOKEN LINK_TOKEN 0x326C977E6efc84E512bB9C30f76E30c160eD06FB)"

log_header "========================================="
log_header "Complete Prerequisites for Bridge Funding"
log_header "========================================="
log_info ""

# Step 1: Check LINK token deployment
log_header "Step 1: Check LINK Token Deployment"
log_info ""

LINK_CODE=$(cast code "$LINK_TOKEN" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$LINK_CODE" ] && [ "$LINK_CODE" != "0x" ]; then
    # Try to verify it's a valid ERC20
    NAME=$(cast call "$LINK_TOKEN" "name()" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    if [ -n "$NAME" ]; then
        log_success "✓ LINK token is deployed and valid"
        log_info "  Address: $LINK_TOKEN"
        log_info "  Name: $NAME"
        LINK_DEPLOYED=true
    else
        log_warn "Contract exists but may not be a valid ERC20 token"
        LINK_DEPLOYED=false
    fi
else
    log_warn "LINK token not deployed"
    LINK_DEPLOYED=false
fi

if [ "$LINK_DEPLOYED" = false ]; then
    log_info ""
    log_info "Attempting to deploy LINK token..."
    if [ -f "$SCRIPT_DIR/deploy-link-token.sh" ]; then
        if "$SCRIPT_DIR/deploy-link-token.sh"; then
            log_success "✓ LINK token deployed successfully"
            LINK_DEPLOYED=true
        else
            log_error "Failed to deploy LINK token"
            log_info "Please deploy manually or check deployment script"
            exit 1
        fi
    else
        log_error "deploy-link-token.sh not found"
        log_info "Please deploy LINK token manually"
        exit 1
    fi
fi

log_info ""
log_header "Step 2: Check Account LINK Balance"
log_info ""

if [ -z "${PRIVATE_KEY:-}" ]; then
    log_error "PRIVATE_KEY not available in effective environment"
    exit 1
fi

ACCOUNT=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || echo "")
if [ -z "$ACCOUNT" ]; then
    log_error "Could not derive address from PRIVATE_KEY"
    exit 1
fi

LINK_BAL=$(cast call "$LINK_TOKEN" "balanceOf(address)" "$ACCOUNT" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
LINK_BAL_ETH=$(cast --from-wei "$LINK_BAL" ether 2>/dev/null || echo "0")

log_info "Account: $ACCOUNT"
log_info "LINK Balance: $LINK_BAL_ETH LINK"

REQUIRED_LINK="20"
if (( $(echo "$LINK_BAL_ETH < $REQUIRED_LINK" | bc -l 2>/dev/null || echo 1) )); then
    log_warn "Insufficient LINK balance"
    log_info "  Current: $LINK_BAL_ETH LINK"
    log_info "  Required: $REQUIRED_LINK LINK"
    log_info "  Needed: $(echo "scale=2; $REQUIRED_LINK - $LINK_BAL_ETH" | bc) LINK"
    log_info ""
    log_info "Options to acquire LINK:"
    log_info "1. If you deployed the token, you should have received the initial supply"
    log_info "2. Transfer LINK from another account"
    log_info "3. Use a faucet (if available on ChainID 138)"
    log_info "4. Bridge LINK from another chain"
    log_info ""
    log_warn "⚠️  Cannot proceed without sufficient LINK balance"
    log_info "Please acquire LINK tokens before continuing"
    exit 1
else
    log_success "✓ Sufficient LINK balance"
fi

log_info ""
log_header "Step 3: Fund Bridge Contracts"
log_info ""

if [ -f "$SCRIPT_DIR/fund-bridge-contracts.sh" ]; then
    log_info "Funding bridge contracts with 10 LINK each..."
    if "$SCRIPT_DIR/fund-bridge-contracts.sh" 10; then
        log_success "✓ Bridge contracts funded successfully"
    else
        log_error "Failed to fund bridge contracts"
        exit 1
    fi
else
    log_error "fund-bridge-contracts.sh not found"
    exit 1
fi

log_info ""
log_header "Step 4: Verify Funding"
log_info ""

# Run funding report
if [ -f "$SCRIPT_DIR/get-funding-report.sh" ]; then
    "$SCRIPT_DIR/get-funding-report.sh" | tail -30
else
    log_warn "get-funding-report.sh not found, skipping verification"
fi

log_info ""
log_header "========================================="
log_header "Prerequisites Complete!"
log_header "========================================="
log_info ""
log_success "✓ LINK token deployed/verified"
log_success "✓ Account has sufficient LINK"
log_success "✓ Bridge contracts funded"
log_info ""
log_info "You can now proceed with bridge operations!"
log_info ""
