#!/bin/bash
# Automated deployment script for MainnetTether and TransactionMirror
# This script will automatically deploy once RPC is configured

set -e

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

cd "$PROJECT_ROOT"
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 [[ -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
fi

# Check required variables
if ! require_private_key_env; then
    exit 1
fi

if [ -z "$ETHEREUM_MAINNET_RPC" ]; then
    echo "ERROR: ETHEREUM_MAINNET_RPC not available. Set it in smom-dbis-138/.env or repo .env." >&2
    exit 1
fi

# Get deployer address
DEPLOYER="$(derive_deployer_address || true)"
if [ -z "$DEPLOYER" ]; then
    echo "ERROR: Could not derive DEPLOYER_ADDRESS from PRIVATE_KEY." >&2
    exit 1
fi

echo "=== MainnetTether & TransactionMirror Deployment ==="
echo ""
echo "Deployer: $DEPLOYER"
echo "Admin: $DEPLOYER (EOA - no multisig)"
echo "RPC: $ETHEREUM_MAINNET_RPC"
echo ""

# Test RPC connection
echo "Testing RPC connection..."
if ! cast block-number --rpc-url "$ETHEREUM_MAINNET_RPC" >/dev/null 2>&1; then
    echo "❌ RPC connection failed!"
    echo ""
    echo "Please fix the Infura RPC configuration:"
    echo "  1. Go to https://infura.io/"
    echo "  2. Project ID: (set in .env as INFURA_PROJECT_ID; use INFURA_PROJECT_SECRET for Basic Auth)"
    echo "  3. Settings → Disable 'Private Key Only'"
    echo "  4. Save and run this script again"
    echo ""
    echo "See: docs/deployment/INFURA_SETTINGS_FIX.md"
    exit 1
fi

echo "✅ RPC connection successful!"
echo ""

# Check balance
BALANCE=$(cast balance $DEPLOYER --rpc-url "$ETHEREUM_MAINNET_RPC" 2>/dev/null || echo "0")
BALANCE_ETH=$(cast --to-unit $BALANCE ether 2>/dev/null || echo "0")
echo "Deployer Balance: $BALANCE_ETH ETH"
echo ""

# Deploy MainnetTether
echo "=== Deploying MainnetTether ==="
LOG_FILE="/tmp/mainnet_tether_deploy.log"
forge script script/DeployMainnetTether.s.sol \
    --rpc-url "$ETHEREUM_MAINNET_RPC" \
    --private-key "$PRIVATE_KEY" \
    --broadcast \
    --verify \
    --via-ir \
    -vvvv 2>&1 | tee "$LOG_FILE"

# Extract MainnetTether address
MAINNET_TETHER=$(grep -oP "MainnetTether deployed at: 0x[a-fA-F0-9]{40}" "$LOG_FILE" 2>/dev/null | grep -oP "0x[a-fA-F0-9]{40}" | head -1)
TETHER_ADMIN=$(grep -oP "Admin: 0x[a-fA-F0-9]{40}" "$LOG_FILE" 2>/dev/null | grep -oP "0x[a-fA-F0-9]{40}" | head -1)

if [ -n "$MAINNET_TETHER" ]; then
    echo ""
    echo "✅ MainnetTether deployed successfully!"
    echo "   Address: $MAINNET_TETHER"
    echo "   Admin: ${TETHER_ADMIN:-$DEPLOYER}"
    echo "   Explorer: https://etherscan.io/address/$MAINNET_TETHER"

    # Update .env
    if grep -q "^MAINNET_TETHER_ADDRESS" .env; then
        sed -i "s|^MAINNET_TETHER_ADDRESS=.*|MAINNET_TETHER_ADDRESS=$MAINNET_TETHER|" .env
    else
        echo "MAINNET_TETHER_ADDRESS=$MAINNET_TETHER" >> .env
    fi
else
    echo ""
    echo "⚠️  MainnetTether deployment may have failed"
    echo "   Check log: $LOG_FILE"
fi

echo ""
echo "=== Deploying TransactionMirror ==="
LOG_FILE="/tmp/transaction_mirror_deploy.log"
forge script script/DeployTransactionMirror.s.sol \
    --rpc-url "$ETHEREUM_MAINNET_RPC" \
    --private-key "$PRIVATE_KEY" \
    --broadcast \
    --verify \
    --via-ir \
    -vvvv 2>&1 | tee "$LOG_FILE"

# Extract TransactionMirror address
TRANSACTION_MIRROR=$(grep -oP "TransactionMirror deployed at: 0x[a-fA-F0-9]{40}" "$LOG_FILE" 2>/dev/null | grep -oP "0x[a-fA-F0-9]{40}" | head -1)
MIRROR_ADMIN=$(grep -oP "Admin: 0x[a-fA-F0-9]{40}" "$LOG_FILE" 2>/dev/null | grep -oP "0x[a-fA-F0-9]{40}" | head -1)

if [ -n "$TRANSACTION_MIRROR" ]; then
    echo ""
    echo "✅ TransactionMirror deployed successfully!"
    echo "   Address: $TRANSACTION_MIRROR"
    echo "   Admin: ${MIRROR_ADMIN:-$DEPLOYER}"
    echo "   Explorer: https://etherscan.io/address/$TRANSACTION_MIRROR"

    # Update .env
    if grep -q "^TRANSACTION_MIRROR_ADDRESS" .env; then
        sed -i "s|^TRANSACTION_MIRROR_ADDRESS=.*|TRANSACTION_MIRROR_ADDRESS=$TRANSACTION_MIRROR|" .env
    else
        echo "TRANSACTION_MIRROR_ADDRESS=$TRANSACTION_MIRROR" >> .env
    fi
else
    echo ""
    echo "⚠️  TransactionMirror deployment may have failed"
    echo "   Check log: $LOG_FILE"
fi

echo ""
echo "=== Deployment Summary ==="
echo ""
if [ -n "$MAINNET_TETHER" ] && [ -n "$TRANSACTION_MIRROR" ]; then
    echo "🎉 Both contracts deployed successfully!"
    echo ""
    echo "MainnetTether:"
    echo "  Address: $MAINNET_TETHER"
    echo "  Explorer: https://etherscan.io/address/$MAINNET_TETHER"
    echo ""
    echo "TransactionMirror:"
    echo "  Address: $TRANSACTION_MIRROR"
    echo "  Explorer: https://etherscan.io/address/$TRANSACTION_MIRROR"
    echo ""
    echo "Next Steps:"
    echo "  1. Verify contracts on Etherscan"
    echo "  2. Set up off-chain services for state anchoring and mirroring"
    echo "  3. Configure monitoring and alerting"
else
    echo "⚠️  Deployment incomplete - check logs for details"
fi
