#!/bin/bash

# Phase 2: Deploy Core Bridge Contracts
# This script deploys core bridge contracts on ChainID 138 and Ethereum

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"
source "$PROJECT_ROOT/scripts/load-env.sh" >/dev/null 2>&1 || true

echo "=== Phase 2: Deploy Core Bridge Contracts ==="

# Check required variables
REQUIRED_VARS=(
    "PRIVATE_KEY"
    "ETHEREUM_MAINNET_RPC"
    "RPC_URL_138"
    "ETHERSCAN_API_KEY"
)

for var in "${REQUIRED_VARS[@]}"; do
    if [ -z "${!var}" ] || [ "${!var}" == "0x..." ] || [ "${!var}" == "your_etherscan_api_key" ]; then
        echo "Error: $var is not set in .env"
        exit 1
    fi
done

echo ""
echo "--- Deploying on ChainID 138 ---"

if [ ! -z "$RPC_URL_138" ] && [ "$RPC_URL_138" != "http://chain138.example.com:8545" ]; then
    echo "Deploying Lockbox on ChainID 138..."
    forge script script/bridge/trustless/DeployTrustlessBridge.s.sol:DeployTrustlessBridge \
        --rpc-url "$RPC_URL_138" \
        --broadcast \
        --via-ir \
        --private-key "$PRIVATE_KEY"
    
    echo ""
    echo "⚠️  Please save LOCKBOX_138 address to .env file"
    echo "   Extract from deployment output above"
else
    echo "⚠️  ChainID 138 RPC not configured, skipping ChainID 138 deployment"
fi

echo ""
echo "--- Deploying on Ethereum Mainnet ---"

echo "Deploying core bridge contracts on Ethereum Mainnet..."
forge script script/bridge/trustless/DeployTrustlessBridge.s.sol:DeployTrustlessBridge \
    --rpc-url "$ETHEREUM_MAINNET_RPC" \
    --broadcast \
    --via-ir \
    --verify \
    --etherscan-api-key "$ETHERSCAN_API_KEY" \
    --private-key "$PRIVATE_KEY"

echo ""
echo "⚠️  Please save all deployed addresses to .env file:"
echo "   - BOND_MANAGER"
echo "   - CHALLENGE_MANAGER"
echo "   - LIQUIDITY_POOL"
echo "   - INBOX_ETH"
echo "   - SWAP_ROUTER"
echo "   - BRIDGE_SWAP_COORDINATOR"
echo ""
echo "Extract addresses from deployment output above"

echo ""
echo "=== Phase 2 Complete ==="
echo "Core bridge contracts deployed"
echo "⚠️  Remember to update .env with all contract addresses"
