#!/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"
# 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_138:-http://localhost:8545}"
GAS_PRICE="${GAS_PRICE:-1000000000}"
PRIVATE_KEY="${PRIVATE_KEY:-}"

if ! require_private_key_env; then
    exit 1
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"
