#!/usr/bin/env bash
# Verify contract deployments in parallel
# Uses .env file for configuration

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
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:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi

# Check required variables
RPC_URL="${RPC_URL:-${RPC_URL_138:-${CHAIN138_RPC_URL:-}}}"
if [ -z "$RPC_URL" ]; then
    log_error "ERROR: Chain 138 RPC not available. Set RPC_URL, RPC_URL_138, or CHAIN138_RPC_URL."
    exit 1
fi

if ! command -v cast &> /dev/null; then
    log_error "Error: cast (Foundry) not found. Install Foundry to verify on-chain deployments."
    exit 1
fi

# Function to verify contract
verify_contract() {
    local name=$1
    local address=$2
    local output_file=$3
    
    if [ -z "$address" ] || [ "$address" = "0x0000000000000000000000000000000000000000" ] || [ "$address" = "" ]; then
        echo "[${name}] ⚠️  Address not set" >> "$output_file"
        return 1
    fi
    
    CODE=$(cast code "$address" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    if [ -n "$CODE" ] && [ "$CODE" != "0x" ] && [ ${#CODE} -gt 2 ]; then
        echo "[${name}] ✅ Deployed at: $address (code length: ${#CODE} chars)" >> "$output_file"
        return 0
    else
        echo "[${name}] ❌ Not found at: $address" >> "$output_file"
        return 1
    fi
}

log_success "=== Parallel Contract Verification ==="
log_warn "Verifying contracts on RPC: $RPC_URL"
echo ""

# Create temp directory for parallel outputs
TEMP_DIR=$(mktemp -d)
declare -A VERIFY_PIDS
FAILED=0

# Verify all contracts in parallel
CONTRACTS=(
    "MULTICALL_ADDRESS:Multicall"
    "WETH9_ADDRESS:WETH9"
    "WETH10_ADDRESS:WETH10"
    "CCIP_ROUTER:CCIP Router"
    "CCIPWETH9BRIDGE_ADDRESS:CCIPWETH9Bridge"
    "CCIPWETH10BRIDGE_ADDRESS:CCIPWETH10Bridge"
    "ORACLE_AGGREGATOR_ADDRESS:Oracle Aggregator"
    "ORACLE_PROXY_ADDRESS:Oracle Proxy"
    "MULTISIG_ADDRESS:MultiSig"
)

for contract_info in "${CONTRACTS[@]}"; do
    IFS=':' read -r env_var name <<< "$contract_info"
    address="${!env_var:-}"
    
    if [ -n "$address" ]; then
        output_file="${TEMP_DIR}/${env_var}.out"
        (
            verify_contract "$name" "$address" "$output_file"
        ) &
        VERIFY_PIDS["$env_var"]=$!
    fi
done

# Wait for all verifications to complete
for env_var in "${!VERIFY_PIDS[@]}"; do
    if ! wait "${VERIFY_PIDS[$env_var]}"; then
        ((FAILED++))
    fi
done

# Display results
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
for contract_info in "${CONTRACTS[@]}"; do
    IFS=':' read -r env_var name <<< "$contract_info"
    output_file="${TEMP_DIR}/${env_var}.out"
    if [ -f "$output_file" ]; then
        cat "$output_file"
    fi
done
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Cleanup
rm -rf "$TEMP_DIR"

# Summary
TOTAL=${#VERIFY_PIDS[@]}
if [ $FAILED -eq 0 ]; then
    log_success "✅ All ${TOTAL} contract(s) verified successfully"
    exit 0
else
    log_error "❌ ${FAILED} out of ${TOTAL} contract(s) failed verification"
    exit 1
fi
