#!/usr/bin/env bash

# Get the mapped address for a genesis address
# Usage: ./get-mapped-address.sh <genesis-address>

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"

source "$PROJECT_ROOT/scripts/load-env.sh" >/dev/null 2>&1 || true

GENESIS_ADDRESS="${1:-}"

if [ -z "$GENESIS_ADDRESS" ]; then
    echo "Usage: $0 <genesis-address>"
    echo ""
    echo "Example:"
    echo "  $0 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
    exit 1
fi

# Check if AddressMapper is deployed
ADDRESS_MAPPER="${ADDRESS_MAPPER:-}"

if [ -z "$ADDRESS_MAPPER" ]; then
    echo "⚠️  ADDRESS_MAPPER not set in .env"
    echo "   Deploy AddressMapper first: bash scripts/forge/scope.sh script utils script/DeployAddressMapper.s.sol:DeployAddressMapper"
    echo ""
    echo "📋 Using static mapping from config/address-mapping.json..."
    
    # Fallback to JSON file
    python3 << EOF
import json
import sys

try:
    with open('config/address-mapping.json', 'r') as f:
        mapping = json.load(f)
    
    genesis_addr = "$GENESIS_ADDRESS".lower()
    
    for name, data in mapping['mappings'].items():
        if data['genesisAddress'].lower() == genesis_addr:
            print(f"✅ Found mapping for {name}:")
            print(f"   Genesis:   {data['genesisAddress']}")
            print(f"   Deployed:  {data['deployedAddress']}")
            print(f"   Reason:    {data['reason']}")
            sys.exit(0)
    
    print(f"❌ No mapping found for {GENESIS_ADDRESS}")
    print("   This address may not be mapped, or AddressMapper needs to be deployed")
    sys.exit(1)
except Exception as e:
    print(f"Error: {e}")
    sys.exit(1)
EOF
else
    echo "🔍 Querying AddressMapper contract..."
    cast call "$ADDRESS_MAPPER" "getDeployedAddress(address)" "$GENESIS_ADDRESS" \
        --rpc-url "${RPC_URL:-http://localhost:8545}" 2>/dev/null | \
        grep -oE "0x[a-fA-F0-9]{40}" | head -1
fi
