#!/usr/bin/env bash
# Extract deployed contract addresses from Foundry broadcast files
# Usage: ./extract-contract-addresses.sh [chain-id]

set -e

SOURCE_PROJECT="${SOURCE_PROJECT:-/home/intlc/projects/smom-dbis-138}"
CHAIN_ID="${1:-138}"

BROADCAST_DIR="$SOURCE_PROJECT/broadcast"
OUTPUT_FILE="$SOURCE_PROJECT/deployed-addresses-chain138.txt"

if [ ! -d "$BROADCAST_DIR" ]; then
    echo "❌ Broadcast directory not found: $BROADCAST_DIR"
    exit 1
fi

echo "Extracting contract addresses from Chain $CHAIN_ID..."
echo ""

# Find latest deployment run
LATEST_RUN=$(find "$BROADCAST_DIR" -type d -path "*/$CHAIN_ID/run-*" | sort -V | tail -1)

if [ -z "$LATEST_RUN" ]; then
    echo "❌ No deployment found for Chain ID $CHAIN_ID"
    exit 1
fi

echo "Found deployment run: $LATEST_RUN"
echo ""

# Extract addresses from broadcast files
{
    echo "# Deployed Contract Addresses - Chain $CHAIN_ID"
    echo "# Generated: $(date)"
    echo ""
    
    # Extract from each deployment script
    for script in "$LATEST_RUN"/*.json; do
        if [ -f "$script" ]; then
            script_name=$(basename "$script" .json)
            address=$(jq -r '.transactions[] | select(.transactionType == "CREATE") | .contractAddress' "$script" 2>/dev/null | head -1)
            if [ -n "$address" ] && [ "$address" != "null" ]; then
                echo "# $script_name"
                echo "${script_name^^}_ADDRESS=$address"
                echo ""
            fi
        fi
    done
} > "$OUTPUT_FILE"

echo "✅ Contract addresses extracted to: $OUTPUT_FILE"
echo ""
cat "$OUTPUT_FILE"

