#!/usr/bin/env bash

# Check what contracts need Mainnet deployment and their dependencies

set -e

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

# Colors

log_info "=== Mainnet Deployment Status Check ==="

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

# Check what's already deployed
log_warn "Checking deployment status..."

# Contracts that need Mainnet deployment
declare -A CONTRACTS=(
    ["CCIPWETH9Bridge"]="MAINNET_CCIP_WETH9_BRIDGE"
    ["CCIPWETH10Bridge"]="MAINNET_CCIP_WETH10_BRIDGE"
    ["CCIPRouter"]="MAINNET_CCIP_ROUTER"
    ["CCIPSender"]="MAINNET_CCIP_SENDER"
    ["CCIPReceiver"]="MAINNET_CCIP_RECEIVER"
    ["OracleAggregator"]="MAINNET_ORACLE_AGGREGATOR"
)

# Dependencies
declare -A DEPENDENCIES=(
    ["CCIPWETH9Bridge"]="CCIPRouter"
    ["CCIPWETH10Bridge"]="CCIPRouter"
    ["CCIPSender"]="CCIPRouter,OracleAggregator"
    ["CCIPReceiver"]="CCIPRouter,OracleAggregator"
)

echo "Contract Deployment Status:"

for contract in "${!CONTRACTS[@]}"; do
    env_var="${CONTRACTS[$contract]}"
    address="${!env_var}"
    deps="${DEPENDENCIES[$contract]:-None}"
    
    if [ -n "$address" ] && [ "$address" != "" ]; then
        printf "  ${GREEN}✅${NC} %-25s %s\n" "$contract" "$address"
    else
        if [ "$deps" != "None" ]; then
            printf "  ${RED}%s${NC} %-25s Not deployed - depends on: %s\n" "❌" "$contract" "$deps"
        else
            printf "  ${RED}%s${NC} %-25s Not deployed\n" "❌" "$contract"
        fi
    fi
done

log_warn "Note: WETH9 and WETH10 already exist on Mainnet at canonical addresses"
echo "  WETH9:  0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
echo "  WETH10: 0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"
