#!/usr/bin/env bash
# Setup Chain-138 environment configuration

set -e

cd "$(dirname "$0")/../.."

# Color codes

echo "=== Setting up Chain-138 Environment ==="

# Load existing .env
if [ -f .env ]; then
    source .env 2>/dev/null || true
fi

# Add Chain-138 RPC if not present
if [ -z "$CHAIN138_RPC_URL" ] || [ "$CHAIN138_RPC_URL" = "" ]; then
    log_info "Adding CHAIN138_RPC_URL to .env..."
    if ! grep -q "^CHAIN138_RPC_URL" .env 2>/dev/null; then
        echo "" >> .env
        echo "# Chain-138 Configuration" >> .env
        echo "CHAIN138_RPC_URL=https://rpc.d-bis.org" >> .env
        log_success "✅ Added CHAIN138_RPC_URL"
    fi
else
    log_success "✅ CHAIN138_RPC_URL already configured"
fi

# Add Chain-138 selector if not present
if [ -z "$CHAIN138_SELECTOR" ] || [ "$CHAIN138_SELECTOR" = "" ]; then
    log_info "Adding CHAIN138_SELECTOR to .env..."
    if ! grep -q "^CHAIN138_SELECTOR" .env 2>/dev/null; then
        echo "CHAIN138_SELECTOR=0x000000000000008a" >> .env
        log_success "✅ Added CHAIN138_SELECTOR"
    fi
else
    log_success "✅ CHAIN138_SELECTOR already configured"
fi

# Add CCIP Router for Chain-138 if not present
if [ -z "$CCIP_CHAIN138_ROUTER" ] || [ "$CCIP_CHAIN138_ROUTER" = "" ]; then
    log_info "Adding CCIP_CHAIN138_ROUTER placeholder..."
    if ! grep -q "^CCIP_CHAIN138_ROUTER" .env 2>/dev/null; then
        echo "# CCIP_CHAIN138_ROUTER=0x..." >> .env
        log_warn "⚠️  CCIP Router address needs to be configured"
    fi
fi

# Add CCIPTxReporter placeholder if not present
if [ -z "$CHAIN138_CCIP_REPORTER" ] || [ "$CHAIN138_CCIP_REPORTER" = "" ]; then
    if ! grep -q "^CHAIN138_CCIP_REPORTER" .env 2>/dev/null; then
        echo "# CHAIN138_CCIP_REPORTER=0x..." >> .env
        log_warn "⚠️  CCIPTxReporter address will be added after deployment"
    fi
fi

log_success "✅ Chain-138 environment setup complete"
echo "Next steps:"
echo "  1. Verify RPC connectivity: ./scripts/deployment/verify-chain138-full-deployment.sh"
echo "  2. If you use the historical CCIPTxReporter flow, set CHAIN138_CCIP_REPORTER in .env"
echo "     Source archive: archive/solidity/contracts/ccip-integration/CCIPTxReporter.sol"
echo "  3. Run verification: ./scripts/deployment/verify-chain138-complete.sh"
