#!/usr/bin/env bash
# Generate Diagnostic Report for Network Administrators
# Creates a comprehensive report with all findings

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

REPORT_DIR="$PROJECT_ROOT/docs/diagnostic-reports"
mkdir -p "$REPORT_DIR"

REPORT_FILE="$REPORT_DIR/network-diagnostic-report-$(date +%Y%m%d-%H%M%S).md"
RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
DEPLOYER=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || echo "")

echo "Generating diagnostic report..."
echo "Report file: $REPORT_FILE"
echo ""

cat > "$REPORT_FILE" << EOF
# Network Diagnostic Report - ChainID 138

**Date**: $(date)
**Generated By**: Network Diagnostic Script
**Purpose**: Contract Deployment Issue Investigation

---

## Executive Summary

**Issue**: All contract deployment attempts are failing on ChainID 138, including minimal 204-byte contracts.

**Status**: ⚠️ **CRITICAL** - Contract creation appears to be blocked at the network level

**Impact**: Cannot deploy LINK token or any other contracts required for CCIP bridge operations

---

## Network Information

- **ChainID**: 138
- **Consensus**: QBFT (Quorum Byzantine Fault Tolerance)
- **Block Period**: 2 seconds
- **Epoch Length**: 30,000 blocks
- **Block Gas Limit**: 30,000,000
- **RPC Endpoint**: $RPC_URL
- **Deployer Address**: $DEPLOYER

---

## Deployment Test Results

### Test 1: MockLinkToken (5M gas)
- **Status**: ❌ FAILED
- **Gas Used**: 5,000,000 (all available)
- **Error**: Transaction reverted (status 0x0)

### Test 2: MockLinkToken (10M gas)
- **Status**: ❌ FAILED
- **Gas Used**: 10,000,000 (all available)
- **Error**: Transaction reverted (status 0x0)
- **Transaction**: 0x4dc9f5eedf580c2b37457916b04048481aba19cf3c1a106ea1ee9eefa0dc03c8

### Test 3: MinimalLink (10M gas)
- **Status**: ❌ FAILED
- **Gas Used**: 10,000,000 (all available)
- **Error**: Transaction reverted (status 0x0)

### Test 4: Minimal Test Contract (204 bytes, 1M gas)
- **Status**: ❌ FAILED
- **Gas Used**: 1,000,000 (all available)
- **Error**: Transaction reverted (status 0x0)
- **Transaction**: 0xc6502cdc4cb2f583fc6b3ddeb8b67b81877cff7a3c1a106ea1ee9eefa0dc03c8

**Pattern**: All deployment attempts consume all available gas and revert with status 0x0.

---

## Configuration Analysis

### RPC Node Configuration

| RPC Type | IP Address | Status | Account Permissioning |
|----------|------------|--------|----------------------|
| Core RPC | 192.168.11.250 | ✅ Accessible | DISABLED |
| Permissioned RPC | 192.168.11.251 | ❌ Not accessible | ENABLED |
| Public RPC | 192.168.11.252 | ❌ Not accessible | DISABLED |

### Account Permissioning

- **File**: \`smom-dbis-138/config/permissions-accounts.toml\`
- **Status**: EMPTY (all accounts allowed)
- **Note**: Empty allowlist means all accounts are permitted

### RPC Node Configurations

- **Core RPC**: \`permissions-accounts-config-file-enabled=false\` ✅
- **Permissioned RPC**: \`permissions-accounts-config-file-enabled=true\` ⚠️
- **Public RPC**: \`permissions-accounts-config-file-enabled=false\` ✅

---

## Network Status

### Current Network State
EOF

# Add current network state
CURRENT_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")
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")

cat >> "$REPORT_FILE" << EOF
- **Current Block**: $CURRENT_BLOCK
- **ChainID**: $CHAIN_ID
- **Deployer Balance**: $BALANCE_ETH ETH
- **Network Status**: ✅ Operational (blocks are being produced)

### Recent Transaction Analysis
EOF

# Add recent transaction analysis
SUCCESS_COUNT=0
FAIL_COUNT=0
CONTRACT_CREATION_COUNT=0

if [ "$CURRENT_BLOCK" != "ERROR" ]; then
    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" --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" --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" --json 2>/dev/null || echo "")
                                if [ -n "$RECEIPT" ]; then
                                    STATUS=$(echo "$RECEIPT" | jq -r '.status // 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
fi

cat >> "$REPORT_FILE" << EOF
- **Successful Transactions**: $SUCCESS_COUNT
- **Failed Transactions**: $FAIL_COUNT
- **Contract Creation Attempts**: $CONTRACT_CREATION_COUNT

---

## Key Findings

1. **Account Permissioning is NOT the Issue**
   - Core RPC has account permissioning DISABLED
   - permissions-accounts.toml is EMPTY (all accounts allowed)
   - Deployer has sufficient balance (999M+ ETH)

2. **All Contract Deployments Fail**
   - Even minimal 204-byte contracts fail
   - All transactions use all available gas and revert
   - Pattern suggests network-level restriction

3. **Network is Operational**
   - Blocks are being produced
   - Regular transactions may work (not tested)
   - Only contract creation appears to be blocked

---

## Requested Actions

1. **Verify Network Configuration**
   - Check if contract creation is restricted at validator level
   - Review Besu configuration on RPC nodes
   - Check for any network-level restrictions

2. **Review Besu Logs**
   - Check RPC node logs for deployment errors
   - Look for transaction rejection reasons
   - Verify if there are permission errors

3. **Test Contract Creation**
   - Attempt to deploy a minimal contract from validator node
   - Verify if contract creation works from different accounts
   - Check if there are account-specific restrictions

4. **Provide Resolution**
   - Enable contract creation if it's disabled
   - Whitelist deployer account if needed
   - Provide alternative deployment method

---

## Diagnostic Scripts

The following scripts were used to generate this report:

1. \`scripts/comprehensive-network-diagnostic.sh\` - Complete network diagnostic
2. \`scripts/verify-rpc-permissions.sh\` - RPC permissioning verification
3. \`scripts/check-besu-logs.sh\` - Besu log analysis

---

## Contact Information

**Deployer Address**: $DEPLOYER
**RPC Endpoint**: $RPC_URL
**Network**: ChainID 138 (DBIS Chain)

---

**Report Generated**: $(date)
**Report Location**: $REPORT_FILE

EOF

echo "✅ Diagnostic report generated: $REPORT_FILE"
echo ""
echo "Report contents:"
head -50 "$REPORT_FILE"
echo ""
echo "... (full report saved to file)"

