#!/usr/bin/env bash
# Deploy all contracts once network is producing blocks
# Usage: ./deploy-contracts-once-ready.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"
FORGE_SCOPE_RUNNER=(bash "$PROJECT_ROOT/scripts/forge/scope.sh")
# 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


RPC_URL="${RPC_URL:-http://localhost:8545}"
PRIVATE_KEY="${PRIVATE_KEY:-}"
NGINX_IP="${NGINX_PROXY_IP:-20.160.58.99}"

if [ -z "$PRIVATE_KEY" ]; then
    echo "❌ Error: PRIVATE_KEY environment variable not set"
    exit 1
fi

# Ensure PRIVATE_KEY has 0x prefix
if [[ ! "$PRIVATE_KEY" =~ ^0x ]]; then
    export PRIVATE_KEY="0x$PRIVATE_KEY"
fi

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Deploy All Contracts - Network Ready"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "RPC URL: $RPC_URL"
echo "Deployer: $(cast wallet address --private-key "$PRIVATE_KEY" 2>/dev/null || echo 'unknown')"
echo ""

# Step 1: Verify network is ready
echo "📋 Step 1: Verifying network is producing blocks..."
BLOCK=$(cast block-number --rpc-url "$RPC_URL" 2>/dev/null | xargs printf "%d" 2>/dev/null || echo "0")
CHAIN=$(cast chain-id --rpc-url "$RPC_URL" 2>/dev/null | xargs printf "%d" 2>/dev/null || echo "0")

if [ "$BLOCK" -eq 0 ]; then
    echo "⚠️  Network is still at block 0"
    echo "   Setting up SSH tunnel..."
    pkill -f "ssh.*8545:10" 2>/dev/null || true
    ssh -o StrictHostKeyChecking=no -f -N -L 8545:10.3.1.4:8545 besuadmin@"$NGINX_IP"
    sleep 3
    BLOCK=$(cast block-number --rpc-url "$RPC_URL" 2>/dev/null | xargs printf "%d" 2>/dev/null || echo "0")
fi

if [ "$BLOCK" -eq 0 ]; then
    echo "❌ Network is not producing blocks yet"
    echo "   Please wait for QBFT validators to initialize"
    echo "   Run this script again once blocks are being produced"
    exit 1
fi

echo "✅ Network is ready!"
echo "   Current block: $BLOCK"
echo "   Chain ID: $CHAIN"
echo ""

# Step 2: Deploy CCIP Infrastructure
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Step 2: Deploy CCIP Infrastructure"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

echo "📋 2.1: Deploy CCIP Router..."
"${FORGE_SCOPE_RUNNER[@]}" script script/DeployCCIPRouter.s.sol:DeployCCIPRouter --rpc-url "$RPC_URL" --broadcast --private-key "$PRIVATE_KEY" --legacy -vvv 2>&1 | tee /tmp/ccip-router.log | grep -E "CCIP Router deployed|deployed at:|Error" | head -3
CCIP_ROUTER=$(grep -oE "0x[a-fA-F0-9]{40}" /tmp/ccip-router.log 2>/dev/null | head -1)
if [ -n "$CCIP_ROUTER" ]; then
    echo "   ✅ CCIP Router: $CCIP_ROUTER"
    sed -i "s|^CCIP_ROUTER_ADDRESS=.*|CCIP_ROUTER_ADDRESS=$CCIP_ROUTER|" .env 2>/dev/null || echo "CCIP_ROUTER_ADDRESS=$CCIP_ROUTER" >> .env
    export CCIP_ROUTER_ADDRESS="$CCIP_ROUTER"
fi

echo ""
echo "📋 2.2: Deploy CCIP Sender..."
"${FORGE_SCOPE_RUNNER[@]}" script script/DeployCCIPSender.s.sol:DeployCCIPSender --rpc-url "$RPC_URL" --broadcast --private-key "$PRIVATE_KEY" --legacy -vvv 2>&1 | tee /tmp/ccip-sender.log | grep -E "CCIPSender deployed|deployed at:|Error" | head -3
CCIP_SENDER=$(grep -oE "0x[a-fA-F0-9]{40}" /tmp/ccip-sender.log 2>/dev/null | head -1)
if [ -n "$CCIP_SENDER" ]; then
    echo "   ✅ CCIP Sender: $CCIP_SENDER"
    sed -i "s|^CCIP_SENDER_ADDRESS=.*|CCIP_SENDER_ADDRESS=$CCIP_SENDER|" .env 2>/dev/null || echo "CCIP_SENDER_ADDRESS=$CCIP_SENDER" >> .env
fi

echo ""
echo "📋 2.3: Deploy CCIP Receiver..."
"${FORGE_SCOPE_RUNNER[@]}" script script/DeployCCIPReceiver.s.sol:DeployCCIPReceiver --rpc-url "$RPC_URL" --broadcast --private-key "$PRIVATE_KEY" --legacy -vvv 2>&1 | tee /tmp/ccip-receiver.log | grep -E "CCIPReceiver deployed|deployed at:|Error" | head -3
CCIP_RECEIVER=$(grep -oE "0x[a-fA-F0-9]{40}" /tmp/ccip-receiver.log 2>/dev/null | head -1)
if [ -n "$CCIP_RECEIVER" ]; then
    echo "   ✅ CCIP Receiver: $CCIP_RECEIVER"
    sed -i "s|^CCIP_RECEIVER_ADDRESS=.*|CCIP_RECEIVER_ADDRESS=$CCIP_RECEIVER|" .env 2>/dev/null || echo "CCIP_RECEIVER_ADDRESS=$CCIP_RECEIVER" >> .env
fi

echo ""
echo "📋 2.4: Deploy CCIP WETH9 Bridge..."
"${FORGE_SCOPE_RUNNER[@]}" script script/DeployCCIPWETH9Bridge.s.sol:DeployCCIPWETH9Bridge --rpc-url "$RPC_URL" --broadcast --private-key "$PRIVATE_KEY" --legacy -vvv 2>&1 | tee /tmp/ccip-weth9-bridge.log | grep -E "CCIPWETH9Bridge deployed|deployed at:|Error" | head -3
WETH9_BRIDGE=$(grep -oE "0x[a-fA-F0-9]{40}" /tmp/ccip-weth9-bridge.log 2>/dev/null | head -1)
if [ -n "$WETH9_BRIDGE" ]; then
    echo "   ✅ CCIP WETH9 Bridge: $WETH9_BRIDGE"
    sed -i "s|^CCIP_WETH9_BRIDGE_ADDRESS=.*|CCIP_WETH9_BRIDGE_ADDRESS=$WETH9_BRIDGE|" .env 2>/dev/null || echo "CCIP_WETH9_BRIDGE_ADDRESS=$WETH9_BRIDGE" >> .env
fi

echo ""
echo "📋 2.5: Deploy CCIP WETH10 Bridge..."
"${FORGE_SCOPE_RUNNER[@]}" script script/DeployCCIPWETH10Bridge.s.sol:DeployCCIPWETH10Bridge --rpc-url "$RPC_URL" --broadcast --private-key "$PRIVATE_KEY" --legacy -vvv 2>&1 | tee /tmp/ccip-weth10-bridge.log | grep -E "CCIPWETH10Bridge deployed|deployed at:|Error" | head -3
WETH10_BRIDGE=$(grep -oE "0x[a-fA-F0-9]{40}" /tmp/ccip-weth10-bridge.log 2>/dev/null | head -1)
if [ -n "$WETH10_BRIDGE" ]; then
    echo "   ✅ CCIP WETH10 Bridge: $WETH10_BRIDGE"
    sed -i "s|^CCIP_WETH10_BRIDGE_ADDRESS=.*|CCIP_WETH10_BRIDGE_ADDRESS=$WETH10_BRIDGE|" .env 2>/dev/null || echo "CCIP_WETH10_BRIDGE_ADDRESS=$WETH10_BRIDGE" >> .env
fi

# Step 3: Deploy Core Contracts
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Step 3: Deploy Core Contracts"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

echo "📋 3.1: Deploy Multicall..."
"${FORGE_SCOPE_RUNNER[@]}" script script/DeployMulticall.s.sol:DeployMulticall --rpc-url "$RPC_URL" --broadcast --private-key "$PRIVATE_KEY" --legacy -vvv 2>&1 | tee /tmp/multicall.log | grep -E "Multicall deployed|deployed at:|Error" | head -3

echo ""
echo "📋 3.2: Deploy Oracle..."
"${FORGE_SCOPE_RUNNER[@]}" script script/DeployOracle.s.sol:DeployOracle --rpc-url "$RPC_URL" --broadcast --private-key "$PRIVATE_KEY" --legacy -vvv 2>&1 | tee /tmp/oracle.log | grep -E "Aggregator|Proxy|deployed at:|Error" | head -5

echo ""
echo "📋 3.3: Deploy MultiSig..."
"${FORGE_SCOPE_RUNNER[@]}" script script/DeployMultiSig.s.sol:DeployMultiSig --rpc-url "$RPC_URL" --broadcast --private-key "$PRIVATE_KEY" --legacy -vvv 2>&1 | tee /tmp/multisig.log | grep -E "MultiSig|deployed at:|Error" | head -3

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✅ Deployment Complete!"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "📋 Deployment addresses saved to .env"
echo ""
