#!/usr/bin/env bash
# Deploy Gnosis Safe multisig wallet
# Usage: ./deploy-multisig.sh <network> <signer1> <signer2> [signer3] [signer4] [signer5] [threshold]

set -euo pipefail

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

source "$PROJECT_ROOT/.env" 2>/dev/null || true

NETWORK="${1:-mainnet}"
SIGNER1="${2:-}"
SIGNER2="${3:-}"
SIGNER3="${4:-}"
SIGNER4="${5:-}"
SIGNER5="${6:-}"
THRESHOLD="${7:-2}"

if [ -z "$SIGNER1" ] || [ -z "$SIGNER2" ]; then
    echo "Usage: $0 <network> <signer1> <signer2> [signer3] [signer4] [signer5] [threshold]"
    echo ""
    echo "Example:"
    echo "  $0 mainnet 0x1111... 0x2222... 0x3333... 2"
    echo "  (Creates 2-of-3 multisig)"
    exit 1
fi

RPC_URL="${ETHEREUM_MAINNET_RPC:-${RPC_URL:-}}"
if [ -z "$RPC_URL" ]; then
    echo "Error: RPC_URL or ETHEREUM_MAINNET_RPC must be set"
    exit 1
fi

echo "Deploying Gnosis Safe multisig..."
echo "Network: $NETWORK"
echo "Signers: $SIGNER1, $SIGNER2${SIGNER3:+, $SIGNER3}${SIGNER4:+, $SIGNER4}${SIGNER5:+, $SIGNER5}"
echo "Threshold: $THRESHOLD"
echo ""

# Build signers array
SIGNERS=("$SIGNER1" "$SIGNER2")
[ -n "$SIGNER3" ] && SIGNERS+=("$SIGNER3")
[ -n "$SIGNER4" ] && SIGNERS+=("$SIGNER4")
[ -n "$SIGNER5" ] && SIGNERS+=("$SIGNER5")

SIGNER_COUNT=${#SIGNERS[@]}

if [ "$THRESHOLD" -gt "$SIGNER_COUNT" ]; then
    echo "Error: Threshold ($THRESHOLD) cannot exceed number of signers ($SIGNER_COUNT)"
    exit 1
fi

echo "Multisig Configuration:"
echo "  Type: ${SIGNER_COUNT}-of-${SIGNER_COUNT} (threshold: $THRESHOLD)"
echo "  Signers: ${SIGNER_COUNT}"
echo ""

echo "⚠️  To deploy Gnosis Safe multisig:"
echo ""
echo "Option 1: Use Gnosis Safe Web Interface (Recommended)"
echo "  1. Go to https://app.safe.global/"
echo "  2. Connect wallet"
echo "  3. Create new Safe"
echo "  4. Add signers: ${SIGNERS[*]}"
echo "  5. Set threshold: $THRESHOLD"
echo "  6. Deploy"
echo ""

echo "Option 2: Use Gnosis Safe SDK"
echo "  Install: npm install @safe-global/safe-core-sdk"
echo "  See: https://docs.safe.global/safe-core-aa-sdk/safe-core-sdk"
echo ""

echo "Option 3: Use Gnosis Safe Factory Contract"
echo "  Factory: 0xa6B71E26C5e0845f74c812102Ca7114b6a896AB2 (Ethereum Mainnet)"
echo "  See: https://docs.safe.global/safe-core-aa-sdk/safe-core-sdk"
echo ""

# Create deployment configuration file
CONFIG_FILE="$SCRIPT_DIR/multisig-config-$(date +%Y%m%d-%H%M%S).json"
cat > "$CONFIG_FILE" <<EOF
{
  "network": "$NETWORK",
  "type": "${SIGNER_COUNT}-of-${SIGNER_COUNT}",
  "threshold": $THRESHOLD,
  "signers": [
$(printf '    "%s"' "${SIGNERS[0]}"
for ((i=1; i<${#SIGNERS[@]}; i++)); do
    echo ","
    printf '    "%s"' "${SIGNERS[$i]}"
done)
  ],
  "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}
EOF

echo "Configuration saved to: $CONFIG_FILE"
echo ""
echo "After deployment:"
echo "1. Save multisig address"
echo "2. Transfer admin rights to multisig"
echo "3. Test multisig operations"
echo "4. Document multisig address"

