#!/bin/bash
# Deploy smart interception update to all translator VMIDs
# Usage: ./scripts/deploy-smart-interception.sh

set -e

echo "═══════════════════════════════════════════════════════════════"
echo "🚀 DEPLOYING SMART INTERCEPTION UPDATE"
echo "═══════════════════════════════════════════════════════════════"
echo ""

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

# Step 1: Build
echo "Step 1: Building TypeScript..."
pnpm run build || npm run build || {
    echo "⚠️  Build failed, trying with npm..."
    npm run build
}

if [ ! -d "dist" ]; then
    echo "❌ Build failed - dist directory not found"
    exit 1
fi

echo "  ✅ Build successful"
echo ""

# Step 2: Deploy to all VMIDs
echo "Step 2: Deploying to all translator VMIDs..."
./scripts/deploy-all-vmids.sh

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "✅ DEPLOYMENT COMPLETE"
echo "═══════════════════════════════════════════════════════════════"
echo ""
echo "Smart interception is now active!"
echo ""
echo "What changed:"
echo "  ✅ Translator checks if address has key in Web3Signer"
echo "  ✅ User wallets (MetaMask) pass through automatically"
echo "  ✅ Service wallets get signed via Web3Signer"
echo ""
echo "Test it:"
echo "  # User wallet (should pass through)"
echo "  curl -X POST http://192.168.11.240:9545 -H 'Content-Type: application/json' -d '{\"jsonrpc\":\"2.0\",\"method\":\"eth_sendTransaction\",\"params\":[{\"from\":\"0x71e81eaec98e507f68bbcf5e2005f179db851603\",\"to\":\"0x0\",\"value\":\"0x0\"}],\"id\":1}'"
echo ""
echo "  # Service wallet (should be intercepted)"
echo "  ADDRESS=\$(curl -s http://192.168.11.111:9000/api/v1/eth1/publicKeys | jq -r '.[0]')"
echo "  curl -X POST http://192.168.11.240:9545 -H 'Content-Type: application/json' -d \"{\\\"jsonrpc\\\":\\\"2.0\\\",\\\"method\\\":\\\"eth_sendTransaction\\\",\\\"params\\\":[{\\\"from\\\":\\\"\$ADDRESS\\\",\\\"to\\\":\\\"0x0\\\",\\\"value\\\":\\\"0x0\\\"}],\\\"id\\\":1}\""
