#!/bin/bash

# Phase 4: Deploy Integration Contracts
# This script deploys peg managers and reserve coordinator

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 4: Deploy Integration Contracts ==="

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

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

echo ""
echo "--- Deploying Integration Contracts ---"

forge script script/bridge/trustless/DeployIntegrationContracts.s.sol:DeployIntegrationContracts \
    --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 "   - STABLECOIN_PEG_MANAGER"
echo "   - COMMODITY_PEG_MANAGER"
echo "   - ISO_CURRENCY_MANAGER"
echo "   - BRIDGE_RESERVE_COORDINATOR"
echo ""
echo "Extract addresses from deployment output above"

echo ""
echo "=== Phase 4 Complete ==="
echo "Integration contracts deployed"
echo "⚠️  Remember to update .env with all contract addresses"
