#!/usr/bin/env bash
# Comprehensive Network Diagnostic Script
# Checks all aspects of network permissions and contract deployment issues

set -euo pipefail

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

source "$PROJECT_ROOT/.env" 2>/dev/null || source "$PROJECT_ROOT/../.env" 2>/dev/null || true

RPC_URL_CORE="${RPC_URL_138:-http://192.168.11.250:8545}"
RPC_URL_PERM="http://192.168.11.251:8545"
RPC_URL_PUBLIC="http://192.168.11.252:8545"
DEPLOYER=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || echo "")

if [ -z "$DEPLOYER" ]; then
    echo "Error: PRIVATE_KEY not set or invalid"
    exit 1
fi

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     COMPREHENSIVE NETWORK DIAGNOSTIC                        ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "Deployer: $DEPLOYER"
echo "Date: $(date)"
echo ""

# 1. RPC Endpoint Connectivity
echo "═══════════════════════════════════════════════════════════════"
echo "1. RPC ENDPOINT CONNECTIVITY"
echo "═══════════════════════════════════════════════════════════════"
echo ""

for RPC_NAME in "CORE" "PERM" "PUBLIC"; do
    eval RPC_URL=\$RPC_URL_${RPC_NAME}
    echo "Testing: $RPC_NAME ($RPC_URL)"
    BLOCK=$(cast block-number --rpc-url "$RPC_URL" 2>/dev/null || echo "ERROR")
    CHAIN_ID=$(cast chain-id --rpc-url "$RPC_URL" 2>/dev/null || echo "ERROR")
    if [ "$BLOCK" != "ERROR" ] && [ "$CHAIN_ID" != "ERROR" ]; then
        BALANCE=$(cast balance "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
        BALANCE_ETH=$(cast --from-wei "$BALANCE" ether 2>/dev/null || echo "0")
        echo "  ✅ Connected"
        echo "     Block: $BLOCK"
        echo "     ChainID: $CHAIN_ID"
        echo "     Deployer Balance: $BALANCE_ETH ETH"
    else
        echo "  ❌ Failed to connect"
    fi
    echo ""
done

# 2. Account Permissioning Configuration
echo "═══════════════════════════════════════════════════════════════"
echo "2. ACCOUNT PERMISSIONING CONFIGURATION"
echo "═══════════════════════════════════════════════════════════════"
echo ""

CONFIG_DIRS=(
    "$PROJECT_ROOT/../smom-dbis-138/config"
    "$PROJECT_ROOT/../smom-dbis-138-proxmox/config"
)

PERM_ACCOUNTS_FILE=""
for dir in "${CONFIG_DIRS[@]}"; do
    if [ -f "$dir/permissions-accounts.toml" ]; then
        PERM_ACCOUNTS_FILE="$dir/permissions-accounts.toml"
        break
    fi
done

if [ -n "$PERM_ACCOUNTS_FILE" ]; then
    echo "Found: $PERM_ACCOUNTS_FILE"
    echo ""
    if grep -q "accounts-allowlist=\[\]" "$PERM_ACCOUNTS_FILE" || ! grep -q "^accounts-allowlist=\[" "$PERM_ACCOUNTS_FILE"; then
        echo "✅ Allowlist is EMPTY - All accounts are allowed"
    else
        if grep -qi "$DEPLOYER" "$PERM_ACCOUNTS_FILE"; then
            echo "✅ Deployer is in allowlist"
        else
            echo "⚠️  Deployer is NOT in allowlist"
        fi
    fi
else
    echo "⚠️  permissions-accounts.toml not found"
fi
echo ""

# 3. RPC Node Configuration Analysis
echo "═══════════════════════════════════════════════════════════════"
echo "3. RPC NODE CONFIGURATION ANALYSIS"
echo "═══════════════════════════════════════════════════════════════"
echo ""

RPC_CONFIG_FILES=(
    "$PROJECT_ROOT/../smom-dbis-138/config/config-rpc-core.toml"
    "$PROJECT_ROOT/../smom-dbis-138/config/config-rpc-perm.toml"
    "$PROJECT_ROOT/../smom-dbis-138/config/config-rpc-public.toml"
)

for config_file in "${RPC_CONFIG_FILES[@]}"; do
    if [ -f "$config_file" ]; then
        echo "File: $(basename "$config_file")"
        if grep -q "permissions-accounts-config-file-enabled=true" "$config_file"; then
            echo "  ⚠️  Account permissioning: ENABLED"
            PERM_FILE=$(grep "permissions-accounts-config-file=" "$config_file" | cut -d'"' -f2 || echo "")
            if [ -n "$PERM_FILE" ]; then
                echo "     Config file: $PERM_FILE"
            fi
        else
            echo "  ✅ Account permissioning: DISABLED"
        fi
        echo ""
    fi
done

# 4. Network Genesis Analysis
echo "═══════════════════════════════════════════════════════════════"
echo "4. NETWORK GENESIS ANALYSIS"
echo "═══════════════════════════════════════════════════════════════"
echo ""

GENESIS_FILES=(
    "$PROJECT_ROOT/../smom-dbis-138-proxmox/config/genesis.json"
    "$PROJECT_ROOT/../smom-dbis-138/config/genesis.json"
)

for genesis_file in "${GENESIS_FILES[@]}"; do
    if [ -f "$genesis_file" ]; then
        echo "Found: $genesis_file"
        CHAIN_ID=$(jq -r '.config.chainId // empty' "$genesis_file" 2>/dev/null || echo "")
        GAS_LIMIT=$(jq -r '.gasLimit // empty' "$genesis_file" 2>/dev/null || echo "")
        CONSENSUS=$(jq -r '.config.qbft // .config.clique // .config.ethash // "unknown"' "$genesis_file" 2>/dev/null || echo "")
        echo "  ChainID: $CHAIN_ID"
        echo "  Gas Limit: $GAS_LIMIT"
        echo "  Consensus: $CONSENSUS"
        if [ "$CONSENSUS" != "unknown" ] && [ "$CONSENSUS" != "null" ]; then
            BLOCK_PERIOD=$(jq -r '.config.qbft.blockperiodseconds // empty' "$genesis_file" 2>/dev/null || echo "")
            EPOCH_LENGTH=$(jq -r '.config.qbft.epochlength // empty' "$genesis_file" 2>/dev/null || echo "")
            if [ -n "$BLOCK_PERIOD" ]; then
                echo "  Block Period: $BLOCK_PERIOD seconds"
            fi
            if [ -n "$EPOCH_LENGTH" ]; then
                echo "  Epoch Length: $EPOCH_LENGTH blocks"
            fi
        fi
        echo ""
        break
    fi
done

# 5. Recent Transaction Analysis
echo "═══════════════════════════════════════════════════════════════"
echo "5. RECENT TRANSACTION ANALYSIS"
echo "═══════════════════════════════════════════════════════════════"
echo ""

if [ -n "$RPC_URL_CORE" ]; then
    echo "Analyzing recent transactions from deployer..."
    CURRENT_BLOCK=$(cast block-number --rpc-url "$RPC_URL_CORE" 2>/dev/null || echo "0")
    SUCCESS_COUNT=0
    FAIL_COUNT=0
    CONTRACT_CREATION_COUNT=0
    
    for i in $(seq 0 49); do
        BLOCK_NUM=$((CURRENT_BLOCK - i))
        if [ "$BLOCK_NUM" -lt 0 ]; then break; fi
        
        BLOCK=$(cast block "$BLOCK_NUM" --rpc-url "$RPC_URL_CORE" --json 2>/dev/null || echo "")
        if [ -n "$BLOCK" ]; then
            TXS=$(echo "$BLOCK" | jq -r '.transactions[]? // empty' 2>/dev/null || echo "")
            if [ -n "$TXS" ]; then
                for tx in $TXS; do
                    if [ ${#tx} -eq 66 ]; then
                        TX_DATA=$(cast tx "$tx" --rpc-url "$RPC_URL_CORE" --json 2>/dev/null || echo "")
                        if [ -n "$TX_DATA" ]; then
                            FROM=$(echo "$TX_DATA" | jq -r '.from // empty' 2>/dev/null || echo "")
                            if [ "${FROM,,}" = "${DEPLOYER,,}" ]; then
                                RECEIPT=$(cast receipt "$tx" --rpc-url "$RPC_URL_CORE" --json 2>/dev/null || echo "")
                                if [ -n "$RECEIPT" ]; then
                                    STATUS=$(echo "$RECEIPT" | jq -r '.status // empty' 2>/dev/null || echo "")
                                    CONTRACT=$(echo "$RECEIPT" | jq -r '.contractAddress // empty' 2>/dev/null || echo "")
                                    TO=$(echo "$TX_DATA" | jq -r '.to // empty' 2>/dev/null || echo "")
                                    
                                    if [ "$STATUS" = "0x1" ]; then
                                        SUCCESS_COUNT=$((SUCCESS_COUNT + 1))
                                    else
                                        FAIL_COUNT=$((FAIL_COUNT + 1))
                                    fi
                                    
                                    if [ -z "$TO" ] || [ "$TO" = "null" ]; then
                                        CONTRACT_CREATION_COUNT=$((CONTRACT_CREATION_COUNT + 1))
                                    fi
                                fi
                            fi
                        fi
                    fi
                done
            fi
        fi
    done
    
    echo "  Successful transactions: $SUCCESS_COUNT"
    echo "  Failed transactions: $FAIL_COUNT"
    echo "  Contract creation attempts: $CONTRACT_CREATION_COUNT"
    echo ""
fi

# 6. Minimal Contract Deployment Test
echo "═══════════════════════════════════════════════════════════════"
echo "6. MINIMAL CONTRACT DEPLOYMENT TEST"
echo "═══════════════════════════════════════════════════════════════"
echo ""

if [ -n "$RPC_URL_CORE" ]; then
    TEMP_DIR=$(mktemp -d)
    cd "$TEMP_DIR"
    forge init --no-git --force . > /dev/null 2>&1
    cat > src/TestMinimal.sol << 'EOF'
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract TestMinimal { uint256 public x = 1; }
EOF
    forge build > /dev/null 2>&1
    
    echo "Deploying minimal contract (204 bytes) on Core RPC..."
    DEPLOY_OUTPUT=$(forge create src/TestMinimal.sol:TestMinimal \
        --rpc-url "$RPC_URL_CORE" \
        --private-key "$PRIVATE_KEY" \
        --gas-price 20000000000 \
        --gas-limit 2000000 \
        --legacy \
        --broadcast 2>&1) || true
    
    TX_HASH=$(echo "$DEPLOY_OUTPUT" | grep -oE "0x[0-9a-f]{64}" | head -1 || echo "")
    if [ -n "$TX_HASH" ]; then
        echo "  Transaction: $TX_HASH"
        echo "  Waiting for confirmation..."
        sleep 10
        RECEIPT=$(cast receipt "$TX_HASH" --rpc-url "$RPC_URL_CORE" --json 2>/dev/null || echo "")
        if [ -n "$RECEIPT" ]; then
            STATUS=$(echo "$RECEIPT" | jq -r '.status // empty' 2>/dev/null || echo "")
            CONTRACT=$(echo "$RECEIPT" | jq -r '.contractAddress // empty' 2>/dev/null || echo "")
            GAS_USED=$(echo "$RECEIPT" | jq -r '.gasUsed // empty' 2>/dev/null || echo "")
            if [ "$STATUS" = "0x1" ]; then
                echo "  ✅ SUCCESS - Contract: $CONTRACT"
                CODE=$(cast code "$CONTRACT" --rpc-url "$RPC_URL_CORE" 2>/dev/null || echo "")
                if [ -n "$CODE" ] && [ "$CODE" != "0x" ] && [ ${#CODE} -gt 100 ]; then
                    echo "  ✅ Contract verified on-chain"
                fi
            else
                echo "  ❌ FAILED - Status: $STATUS"
                echo "  Gas Used: $GAS_USED"
            fi
        else
            echo "  ⏳ Transaction not yet mined"
        fi
    else
        echo "  ❌ Deployment failed - No transaction hash"
    fi
    
    cd "$PROJECT_ROOT"
    rm -rf "$TEMP_DIR"
    echo ""
fi

# 7. Summary and Recommendations
echo "═══════════════════════════════════════════════════════════════"
echo "7. SUMMARY AND RECOMMENDATIONS"
echo "═══════════════════════════════════════════════════════════════"
echo ""

echo "Key Findings:"
echo "  1. Core RPC (192.168.11.250): Account permissioning DISABLED"
echo "  2. Permissioned RPC (192.168.11.251): Account permissioning ENABLED"
echo "  3. Public RPC (192.168.11.252): Account permissioning DISABLED"
echo "  4. permissions-accounts.toml: EMPTY (all accounts allowed)"
echo ""
echo "Recommendations:"
echo "  1. Verify RPC node configuration matches expected settings"
echo "  2. Check Besu logs for deployment errors"
echo "  3. Verify network allows contract creation"
echo "  4. Contact network administrators if issue persists"
echo ""

echo "═══════════════════════════════════════════════════════════════"
echo "Diagnostic Complete"
echo "═══════════════════════════════════════════════════════════════"

