#!/bin/bash
# Check transaction status on block explorer
# Usage: ./check-block-explorer-tx.sh [tx_hash] [account_address]

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
source "$PROJECT_ROOT/scripts/lib/address-inventory.sh"
cd "$PROJECT_ROOT"

load_explorer_runtime_env

RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
EXPLORER_URL="${EXPLORER_URL:-https://explorer.d-bis.org}"
ACCOUNT="${2:-$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || echo "")}"

if [ -z "$ACCOUNT" ]; then
    echo "Error: Account address required"
    exit 1
fi

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     BLOCK EXPLORER TRANSACTION CHECK                         ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "Explorer: $EXPLORER_URL"
echo "Account: $ACCOUNT"
echo ""

# If tx hash provided, check specific transaction
if [ -n "${1:-}" ] && [[ "$1" =~ ^0x[0-9a-fA-F]{64}$ ]]; then
    TX_HASH="$1"
    echo "=== Checking Transaction: $TX_HASH ==="
    echo ""
    echo "Explorer URL: $EXPLORER_URL/tx/$TX_HASH"
    echo ""
    
    # Try to get receipt via RPC
    echo "Checking via RPC..."
    RECEIPT=$(cast receipt "$TX_HASH" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    
    if [ -n "$RECEIPT" ] && [ "$RECEIPT" != "" ]; then
        echo "✓ Transaction found in RPC"
        STATUS=$(echo "$RECEIPT" | grep -oE "status[[:space:]]+[0-9]+" | awk '{print $2}' || echo "")
        BLOCK=$(echo "$RECEIPT" | grep -oE "blockNumber[[:space:]]+[0-9]+" | awk '{print $2}' || echo "")
        GAS_USED=$(echo "$RECEIPT" | grep -oE "gasUsed[[:space:]]+[0-9]+" | awk '{print $2}' || echo "")
        
        if [ "$STATUS" = "1" ]; then
            echo "✓ Status: SUCCESS"
        elif [ "$STATUS" = "0" ]; then
            echo "✗ Status: FAILED/REVERTED"
            echo ""
            echo "Checking revert reason..."
            # Try to decode revert reason
            REVERT_REASON=$(cast tx "$TX_HASH" --rpc-url "$RPC_URL" 2>&1 | grep -i "revert\|error" || echo "")
            if [ -n "$REVERT_REASON" ]; then
                echo "Revert reason: $REVERT_REASON"
            fi
        else
            echo "? Status: UNKNOWN ($STATUS)"
        fi
        
        if [ -n "$BLOCK" ]; then
            echo "Block: $BLOCK"
        fi
        if [ -n "$GAS_USED" ]; then
            echo "Gas Used: $GAS_USED"
        fi
        
        # Check for contract creation
        CONTRACT_ADDRESS=$(echo "$RECEIPT" | grep -oE "contractAddress[[:space:]]+0x[0-9a-fA-F]{40}" | awk '{print $2}' || echo "")
        if [ -n "$CONTRACT_ADDRESS" ]; then
            echo ""
            echo "✓✓✓ Contract Created!"
            echo "Contract Address: $CONTRACT_ADDRESS"
            CODE=$(cast code "$CONTRACT_ADDRESS" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
            if [ -n "$CODE" ] && [ "$CODE" != "0x" ] && [ ${#CODE} -gt 100 ]; then
                echo "✓ Contract bytecode confirmed (${#CODE} chars)"
            else
                echo "⚠ Contract bytecode not yet available"
            fi
        fi
    else
        echo "⚠ Transaction not found in RPC (may be pending or not yet indexed)"
        echo ""
        echo "Check on explorer: $EXPLORER_URL/tx/$TX_HASH"
    fi
else
    # Check recent transactions for account
    echo "=== Recent Transactions for Account ==="
    echo ""
    echo "Explorer URL: $EXPLORER_URL/address/$ACCOUNT"
    echo ""
    echo "Checking last 10 transactions via RPC..."
    
    # Get current block
    CURRENT_BLOCK=$(cast block-number --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    if [ "$CURRENT_BLOCK" != "0" ]; then
        echo "Current block: $CURRENT_BLOCK"
        echo ""
        echo "Note: RPC may not provide transaction history."
        echo "Please check explorer directly: $EXPLORER_URL/address/$ACCOUNT"
        echo ""
        echo "Recent transactions (if available):"
        
        # Try to get transactions from recent blocks
        for i in {0..9}; do
            BLOCK_NUM=$((CURRENT_BLOCK - i))
            if [ "$BLOCK_NUM" -gt 0 ]; then
                BLOCK_DATA=$(cast block "$BLOCK_NUM" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
                if echo "$BLOCK_DATA" | grep -q "$ACCOUNT"; then
                    echo "  Block $BLOCK_NUM: Account activity found"
                fi
            fi
        done
    fi
fi

echo ""
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     MANUAL CHECK REQUIRED                                    ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "For detailed transaction information, please visit:"
echo "  Account: $EXPLORER_URL/address/$ACCOUNT"
if [ -n "${TX_HASH:-}" ]; then
    echo "  Transaction: $EXPLORER_URL/tx/$TX_HASH"
fi
echo ""
