#!/usr/bin/env bash

# Verify deployed contracts on Etherscan using ETHERSCAN_API_KEY

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# 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

log_info "=== Etherscan Contract Verification ==="

if [ -z "$ETHERSCAN_API_KEY" ]; then
    log_error "ERROR: ETHERSCAN_API_KEY not available. Set it in smom-dbis-138/.env or repo .env."
    exit 1
fi

# Function to verify contract
verify_contract() {
    local contract_address=$1
    local contract_name=$2
    local source_code=$3
    
    log_warn "Verifying $contract_name at $contract_address..."
    
    # Etherscan verification API
    local response=$(curl -s -X POST "https://api.etherscan.io/api" \
        -d "apikey=$ETHERSCAN_API_KEY" \
        -d "module=contract" \
        -d "action=verifysourcecode" \
        -d "address=$contract_address" \
        -d "sourceCode=$source_code" \
        -d "codeformat=solidity-single-file" 2>/dev/null || echo "")
    
    if [ -n "$response" ]; then
        local status=$(echo "$response" | jq -r '.status' 2>/dev/null || echo "")
        if [ "$status" == "1" ]; then
            log_success "✅ Verification submitted"
            return 0
        else
            local message=$(echo "$response" | jq -r '.message' 2>/dev/null || echo "")
            log_warn "⚠️  $message"
            return 1
        fi
    else
        log_error "❌ Verification failed"
        return 1
    fi
}

echo "This script helps verify contracts on Etherscan."
echo "For full verification, use Foundry's verify command:"
echo "  forge verify-contract <address> <contract> --chain-id 1 --etherscan-api-key \$ETHERSCAN_API_KEY"
echo "Example:"
echo "  forge verify-contract \$CCIP_WETH9_BRIDGE CCIPWETH9Bridge --chain-id 1 --etherscan-api-key \$ETHERSCAN_API_KEY"
