#!/usr/bin/env bash
# Update service .env files with deployed contract addresses
# Usage: ./update-service-configs.sh <contract-addresses-file>

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ADDRESSES_FILE="${1:-/home/intlc/projects/smom-dbis-138/deployed-addresses-chain138.txt}"

if [ ! -f "$ADDRESSES_FILE" ]; then
    echo "❌ Addresses file not found: $ADDRESSES_FILE"
    exit 1
fi

# Source addresses
source "$ADDRESSES_FILE" 2>/dev/null || true

RPC_URL="http://192.168.11.250:8545"
WS_URL="ws://192.168.11.250:8546"

# Function to update container .env
update_container_env() {
    local vmid="$1"
    local service_name="$2"
    local env_content="$3"
    
    if ! pct status "$vmid" &>/dev/null; then
        echo "⚠️  Container $vmid not found, skipping $service_name"
        return
    fi
    
    echo "Updating $service_name (VMID $vmid)..."
    pct exec "$vmid" -- bash -c "cat > /opt/$service_name/.env <<'ENVEOF'
$env_content
ENVEOF" 2>/dev/null && echo "✅ Updated $service_name" || echo "❌ Failed to update $service_name"
}

# Oracle Publisher (VMID 3500)
if [ -n "$ORACLE_CONTRACT_ADDRESS" ] || [ -n "$AGGREGATOR_ADDRESS" ]; then
    ORACLE_ADDR="${ORACLE_CONTRACT_ADDRESS:-$AGGREGATOR_ADDRESS}"
    update_container_env 3500 "oracle-publisher" "RPC_URL_138=$RPC_URL
WS_URL_138=$WS_URL
ORACLE_CONTRACT_ADDRESS=$ORACLE_ADDR
PRIVATE_KEY=\${PRIVATE_KEY}
UPDATE_INTERVAL=60
METRICS_PORT=8000"
fi

# CCIP Monitor (VMID 3501)
if [ -n "$CCIP_ROUTER_ADDRESS" ] && [ -n "$CCIP_SENDER_ADDRESS" ]; then
    update_container_env 3501 "ccip-monitor" "RPC_URL_138=$RPC_URL
CCIP_ROUTER_ADDRESS=$CCIP_ROUTER_ADDRESS
CCIP_SENDER_ADDRESS=$CCIP_SENDER_ADDRESS
LINK_TOKEN_ADDRESS=\${LINK_TOKEN_ADDRESS}
METRICS_PORT=8000
CHECK_INTERVAL=60"
fi

# Keeper (VMID 3502)
if [ -n "$PRICE_FEED_KEEPER_ADDRESS" ]; then
    update_container_env 3502 "keeper" "RPC_URL_138=$RPC_URL
PRICE_FEED_KEEPER_ADDRESS=$PRICE_FEED_KEEPER_ADDRESS
KEEPER_PRIVATE_KEY=\${KEEPER_PRIVATE_KEY}
UPDATE_INTERVAL=300
HEALTH_PORT=3000"
fi

# Financial Tokenization (VMID 3503)
if [ -n "$RESERVE_SYSTEM_ADDRESS" ]; then
    update_container_env 3503 "financial-tokenization" "FIREFLY_API_URL=http://192.168.11.66:5000
FIREFLY_API_KEY=\${FIREFLY_API_KEY}
BESU_RPC_URL=$RPC_URL
CHAIN_ID=138
RESERVE_SYSTEM=$RESERVE_SYSTEM_ADDRESS
FLASK_ENV=production
FLASK_PORT=5001"
fi

echo ""
echo "✅ Service configurations updated"
echo ""
echo "Note: Private keys and API keys need to be set manually"

