#!/bin/bash

# Phase 7: Configure Access Control and Routing
# This script configures access control roles and routing logic

set -e

echo "=== Phase 7: Configure Access Control and Routing ==="

# Load environment variables
if [ -f .env ]; then
    export $(cat .env | grep -v '^#' | grep -v '^$' | xargs)
fi

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

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 "--- Configuring Access Control Roles ---"

# Grant COORDINATOR_ROLE to BridgeSwapCoordinator
COORDINATOR_ROLE=$(cast keccak "COORDINATOR_ROLE" 2>/dev/null || echo "0x")

if [ "$COORDINATOR_ROLE" != "0x" ]; then
    echo "Granting COORDINATOR_ROLE to BridgeSwapCoordinator..."
    cast send "$ENHANCED_SWAP_ROUTER" \
        "grantRole(bytes32,address)" \
        "$COORDINATOR_ROLE" \
        "$BRIDGE_SWAP_COORDINATOR" \
        --rpc-url "$ETHEREUM_MAINNET_RPC" \
        --private-key "$PRIVATE_KEY"
    echo "✓ COORDINATOR_ROLE granted"
else
    echo "⚠️  Could not compute COORDINATOR_ROLE hash"
fi

echo ""
echo "--- Routing Logic Configuration ---"
echo "EnhancedSwapRouter is pre-configured with default routing:"
echo "  - Small swaps (< \$10k): Uniswap V3, Dodoex"
echo "  - Medium swaps (\$10k-\$100k): Dodoex, Balancer, Uniswap V3"
echo "  - Large swaps (> \$100k): Dodoex, Curve, Balancer"
echo ""
echo "To customize routing, use:"
echo "cast send \$ENHANCED_SWAP_ROUTER \\"
echo "  \"setRoutingConfig(uint256,uint8[])\" \\"
echo "  <sizeIndex> \\"
echo "  \"[<provider1>,<provider2>]\" \\"
echo "  --rpc-url \$ETHEREUM_MAINNET_RPC \\"
echo "  --private-key \$PRIVATE_KEY"

echo ""
echo "=== Phase 7 Complete ==="
echo "Access control and routing configured"

