#!/usr/bin/env bash
# Analyze transaction on ChainID 138
# Usage: ./analyze-transaction-138.sh <tx_hash>

set -euo pipefail

TX_HASH="${1:-0x789a8f3957f793b00f00e6907157c15156d1fab35a70db9476ef5ddcdce7c044}"
RPC_URL="https://rpc-http-pub.d-bis.org"
EXPLORER_URL="https://explorer.d-bis.org"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

info() { echo -e "${BLUE}[INFO]${NC} $1"; }
success() { echo -e "${GREEN}[✓]${NC} $1"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }

echo "=========================================="
echo "Transaction Analysis - ChainID 138"
echo "=========================================="
echo "Hash: $TX_HASH"
echo ""

# Check via RPC
info "Checking via RPC..."
TX_RESULT=$(curl -s -X POST "$RPC_URL" \
  -H "Content-Type: application/json" \
  -d "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransactionByHash\",\"params\":[\"$TX_HASH\"],\"id\":1}" | jq -r '.result // "null"')

if [[ "$TX_RESULT" != "null" && "$TX_RESULT" != "" ]]; then
    success "Transaction found via RPC!"
    echo ""
    echo "Transaction Details:"
    echo "$TX_RESULT" | jq '{
        hash: .hash,
        from: .from,
        to: .to,
        value: .value,
        blockNumber: .blockNumber,
        blockHash: .blockHash,
        transactionIndex: .transactionIndex,
        gas: .gas,
        gasPrice: .gasPrice,
        input: .input
    }'
else
    warn "Transaction not found via RPC"
    echo "  This could mean:"
    echo "    - Transaction is pending (not yet mined)"
    echo "    - Transaction failed before being mined"
    echo "    - RPC node needs to sync more blocks"
    echo "    - Transaction is in a block that hasn't been indexed"
fi

echo ""

# Check receipt
info "Checking transaction receipt..."
RECEIPT=$(curl -s -X POST "$RPC_URL" \
  -H "Content-Type: application/json" \
  -d "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getTransactionReceipt\",\"params\":[\"$TX_HASH\"],\"id\":1}" | jq -r '.result // "null"')

if [[ "$RECEIPT" != "null" && "$RECEIPT" != "" ]]; then
    success "Receipt found!"
    echo ""
    echo "Receipt Details:"
    echo "$RECEIPT" | jq '{
        status: (if .status == "0x1" then "Success" else "Failed" end),
        blockNumber: .blockNumber,
        blockHash: .blockHash,
        gasUsed: .gasUsed,
        effectiveGasPrice: .effectiveGasPrice,
        contractAddress: .contractAddress,
        logsCount: (.logs | length),
        to: .to,
        from: .from
    }'
    
    # Check if it's a contract creation
    if [[ $(echo "$RECEIPT" | jq -r '.contractAddress // "null"') != "null" ]]; then
        echo ""
        info "Contract Creation Detected!"
        echo "  Contract Address: $(echo "$RECEIPT" | jq -r '.contractAddress')"
    fi
    
    # Show logs if any
    LOGS_COUNT=$(echo "$RECEIPT" | jq '.logs | length')
    if [[ "$LOGS_COUNT" -gt 0 ]]; then
        echo ""
        info "Transaction emitted $LOGS_COUNT event(s)"
        echo "$RECEIPT" | jq '.logs[] | {address: .address, topics: .topics[0], dataLength: (.data | length)}' | head -20
    fi
else
    warn "Receipt not found"
fi

echo ""
echo "=========================================="
info "Explorer Links:"
echo "  Blockscout: $EXPLORER_URL/tx/$TX_HASH"
echo "  Direct API: $EXPLORER_URL/api/v1/transactions/$TX_HASH"
echo ""
info "To get full details, visit the explorer or use the API directly"

