#!/usr/bin/env bash
# Complete monitoring setup

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
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 [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi


log_info "=== Complete Monitoring Setup ==="

# Load environment
if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"
fi

log_info "1. Etherscan Monitoring"
echo "   Contracts to monitor:"
WETH9=$(grep "CCIPWETH9_BRIDGE_MAINNET=" "$PROJECT_ROOT/.env" 2>/dev/null | cut -d'=' -f2 | tr -d ' "' || echo "")
WETH10=$(grep "CCIPWETH10_BRIDGE_MAINNET=" "$PROJECT_ROOT/.env" 2>/dev/null | cut -d'=' -f2 | tr -d ' "' || echo "")
LOGGER=$(grep "CCIP_LOGGER_ETH_ADDRESS=" "$PROJECT_ROOT/.env" 2>/dev/null | cut -d'=' -f2 | tr -d ' "' || echo "")

if [ -n "$WETH9" ]; then
    echo "   • CCIPWETH9Bridge: https://etherscan.io/address/$WETH9"
fi
if [ -n "$WETH10" ]; then
    echo "   • CCIPWETH10Bridge: https://etherscan.io/address/$WETH10"
fi
if [ -n "$LOGGER" ]; then
    echo "   • CCIPLogger: https://etherscan.io/address/$LOGGER"
fi

log_info "2. Event Monitoring"
echo "   Key events to monitor:"
echo "   • CrossChainTransferInitiated"
echo "   • CrossChainTransferCompleted"
echo "   • CrossChainTransferFailed"
echo "   • RemoteTxLogged (CCIPLogger)"
echo "   • RemoteBatchLogged (CCIPLogger)"

log_info "3. Balance Monitoring"
echo "   Create monitoring script for:"
echo "   • Bridge LINK balances (CCIP fees)"
echo "   • Bridge WETH balances"
echo "   • Alert thresholds"

log_info "4. CCIP Message Tracking"
echo "   Monitor via:"
echo "   • Chainlink CCIP Explorer"
echo "   • Contract events"
echo "   • Message status queries"

log_success "✅ Monitoring setup guide created"
echo "Next steps:"
echo "  1. Set up Etherscan alerts"
echo "  2. Create event monitoring scripts"
echo "  3. Set up balance alerts"
echo "  4. Configure CCIP message tracking"
