#!/usr/bin/env bash
# Find all contracts deployed to Ethereum Mainnet
# Searches broadcast files, .env, and Etherscan API

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"
# 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


echo "=========================================="
echo "Finding All Deployed Mainnet Contracts"
echo "=========================================="
echo ""

# Get deployer address
if [ -n "${PRIVATE_KEY:-}" ]; then
    PRIVATE_KEY_FIXED="${PRIVATE_KEY}"
    [[ "$PRIVATE_KEY_FIXED" != 0x* ]] && PRIVATE_KEY_FIXED="0x${PRIVATE_KEY_FIXED}"
    DEPLOYER=$(cast wallet address "$PRIVATE_KEY_FIXED" 2>/dev/null | head -1)
    echo "Deployer: $DEPLOYER"
    echo ""
else
    echo "⚠️  PRIVATE_KEY not set"
    DEPLOYER=""
fi

echo "=== Method 1: Broadcast Files ==="
if [ -d "broadcast" ]; then
    MAINNET_FILES=$(find broadcast -path "*/1/*.json" -o -path "*mainnet/*.json" 2>/dev/null | head -10)
    if [ -n "$MAINNET_FILES" ]; then
        for file in $MAINNET_FILES; do
            echo "Checking $file..."
            jq -r '.transactions[]? | select(.transactionType == "CREATE") | "  \(.contractName): \(.contractAddress)"' "$file" 2>/dev/null
        done
    else
        echo "  No Mainnet broadcast files found"
    fi
else
    echo "  No broadcast directory"
fi
echo ""

echo "=== Method 2: .env File ==="
grep -E "^[A-Z_]+.*=0x[a-fA-F0-9]{40}" .env 2>/dev/null | grep -iE "mainnet|MAINNET" | while IFS= read -r line; do
    key=$(echo "$line" | cut -d'=' -f1)
    addr=$(echo "$line" | cut -d'=' -f2)
    echo "  $key: $addr"
done
echo ""

echo "=== Method 3: Etherscan API ==="
if [ -n "$DEPLOYER" ] && [ -n "${ETHERSCAN_API_KEY:-}" ]; then
    echo "Fetching contracts created by $DEPLOYER..."
    RESPONSE=$(curl -s "https://api.etherscan.io/api?module=account&action=txlist&address=$DEPLOYER&startblock=0&endblock=99999999&sort=asc&apikey=$ETHERSCAN_API_KEY")

    CONTRACTS=$(echo "$RESPONSE" | jq -r '.result[] | select(.to == "" or .to == null) | "\(.contractAddress) | Block: \(.blockNumber) | \(.timeStamp | tonumber | strftime("%Y-%m-%d"))"' 2>/dev/null)

    if [ -n "$CONTRACTS" ]; then
        echo "$CONTRACTS" | while IFS= read -r contract; do
            addr=$(echo "$contract" | cut -d'|' -f1 | xargs)
            echo "  $contract"
            # Try to get contract name
            CONTRACT_INFO=$(curl -s "https://api.etherscan.io/api?module=contract&action=getsourcecode&address=$addr&apikey=$ETHERSCAN_API_KEY")
            NAME=$(echo "$CONTRACT_INFO" | jq -r '.result[0].ContractName' 2>/dev/null)
            if [ -n "$NAME" ] && [ "$NAME" != "" ] && [ "$NAME" != "null" ]; then
                echo "    Contract Name: $NAME"
            fi
        done
    else
        echo "  No contracts found"
    fi
else
    echo "  Cannot check (missing PRIVATE_KEY or ETHERSCAN_API_KEY)"
fi
echo ""

echo "=========================================="
echo "Search Complete"
echo "=========================================="

