#!/usr/bin/env bash
# Extract Contract Address from Forge Deployment
# Helper script to extract contract addresses from Forge deployment output

set -euo pipefail

# Colors for output

# Usage
usage() {
    echo "Usage: $0 <deployment_output_file> <contract_name>"
    echo "Example: $0 deploy.log WETH"
    exit 1
}

# Check arguments
if [ $# -lt 2 ]; then
    usage
fi

DEPLOYMENT_OUTPUT="$1"
CONTRACT_NAME="$2"

# Check if file exists
if [ ! -f "$DEPLOYMENT_OUTPUT" ]; then
    log_error "Error: Deployment output file not found: $DEPLOYMENT_OUTPUT"
    exit 1
fi

# Extract contract address
ADDRESS=$(grep -i "Contract deployed at:" "$DEPLOYMENT_OUTPUT" | grep -oP '0x[a-fA-F0-9]{40}' | head -n 1 || \
    grep -i "Deployed to:" "$DEPLOYMENT_OUTPUT" | grep -oP '0x[a-fA-F0-9]{40}' | head -n 1 || \
    echo "")

if [ -z "$ADDRESS" ]; then
    # Try to extract from broadcast log
    BROADCAST_LOG="broadcast/Deploy${CONTRACT_NAME}.s.sol/138/run-latest.json"
    if [ -f "$BROADCAST_LOG" ]; then
        ADDRESS=$(jq -r '.transactions[] | select(.contractName == "'"$CONTRACT_NAME"'") | .contractAddress' "$BROADCAST_LOG" | head -n 1 || echo "")
    fi
fi

if [ -z "$ADDRESS" ]; then
    log_error "Error: Could not extract contract address for $CONTRACT_NAME"
    exit 1
fi

echo "$ADDRESS"

