#!/usr/bin/env bash
# Deploy all contracts in parallel where possible
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"

source .env 2>/dev/null || true

RPC_URL="${RPC_URL_138:-http://localhost:8545}"
GAS_PRICE="${GAS_PRICE:-1000000000}"
PRIVATE_KEY="${PRIVATE_KEY:-}"

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"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "RPC URL: $RPC_URL"
echo ""

# Phase 1: Core Infrastructure (already deployed)
echo "✅ Phase 1: Core Infrastructure"
echo "   • WETH9: Pre-deployed in genesis"
echo "   • WETH10: Pre-deployed in genesis"
echo ""

# Phase 2: Utility Contracts
echo "📋 Phase 2: Utility Contracts"
echo "   Deploying Multicall..."
forge script script/DeployMulticall.s.sol:DeployMulticall \
    --rpc-url "$RPC_URL" \
    --broadcast \
    --private-key "$PRIVATE_KEY" \
    --with-gas-price "$GAS_PRICE" \
    --legacy -vvv 2>&1 | tail -30

# Phase 3: Oracle Contracts
echo ""
echo "📋 Phase 3: Oracle Contracts"
echo "   Deploying Oracle..."
forge script script/DeployOracle.s.sol:DeployOracle \
    --rpc-url "$RPC_URL" \
    --broadcast \
    --private-key "$PRIVATE_KEY" \
    --with-gas-price "$GAS_PRICE" \
    --legacy -vvv 2>&1 | tail -30

# Phase 4: Governance Contracts
echo ""
echo "📋 Phase 4: Governance Contracts"
echo "   Deploying MultiSig..."
forge script script/DeployMultiSig.s.sol:DeployMultiSig \
    --rpc-url "$RPC_URL" \
    --broadcast \
    --private-key "$PRIVATE_KEY" \
    --with-gas-price "$GAS_PRICE" \
    --legacy -vvv 2>&1 | tail -30

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✅ Core Contracts Deployment Complete"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "📋 Next: Deploy CCIP infrastructure"
echo "   • CCIP Router"
echo "   • CCIP Sender/Receiver"
echo "   • CCIP Bridges"
