#!/bin/bash
# Check if network allows contract creation
# Verifies CREATE opcode and deployment restrictions

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}"
ACCOUNT=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || echo "")

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

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     NETWORK RESTRICTION CHECK                                  ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "RPC: $RPC_URL"
echo "Account: $ACCOUNT"
echo ""

# Check network status
echo "=== Network Status ==="
BLOCK=$(cast block-number --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
CHAIN_ID=$(cast chain-id --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
echo "Block: $BLOCK"
echo "Chain ID: $CHAIN_ID"
echo ""

# Check account balance
echo "=== Account Status ==="
BALANCE=$(cast balance "$ACCOUNT" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
BALANCE_ETH=$(cast --from-wei "$BALANCE" ether 2>/dev/null || echo "0")
NONCE=$(cast nonce "$ACCOUNT" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
echo "Balance: $BALANCE_ETH ETH"
echo "Nonce: $NONCE"
echo ""

# Test contract creation with minimal contract
echo "=== Testing Contract Creation ==="
echo "Attempting to deploy minimal test contract..."

TEMP_DIR=$(mktemp -d)
cd "$TEMP_DIR"

# Initialize forge project
forge init --no-git --force . > /dev/null 2>&1

# Create minimal test contract
cat > src/TestContract.sol << 'EOF'
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

contract TestContract {
    uint256 public value = 42;
}
EOF

# Build
forge build > /dev/null 2>&1

# Get bytecode
BYTECODE=$(cat out/TestContract.sol/TestContract.json | jq -r '.bytecode.object' 2>/dev/null || echo "")

if [ -n "$BYTECODE" ] && [ "$BYTECODE" != "null" ] && [ ${#BYTECODE} -gt 100 ]; then
    echo "✓ Got test contract bytecode (${#BYTECODE} chars)"
    echo ""
    echo "Attempting deployment with high gas..."
    
    FORCE_GAS="5000000000"  # 5 gwei
    CURRENT_NONCE=$(cast nonce "$ACCOUNT" --rpc-url "$RPC_URL")
    
    echo "Gas: $FORCE_GAS wei ($(echo "scale=2; $FORCE_GAS / 1000000000" | bc) gwei)"
    echo "Nonce: $CURRENT_NONCE"
    echo ""
    
    # Try deployment
    TX_OUTPUT=$(timeout 30 cast send --create "$BYTECODE" \
        --rpc-url "$RPC_URL" \
        --private-key "$PRIVATE_KEY" \
        --gas-price "$FORCE_GAS" \
        --nonce "$CURRENT_NONCE" \
        --legacy 2>&1 || echo "FAILED")
    
    if echo "$TX_OUTPUT" | grep -qE "(blockHash|transactionHash|contractAddress)"; then
        echo "✓✓✓ Test contract deployment transaction sent!"
        TX_HASH=$(echo "$TX_OUTPUT" | grep -oE "0x[0-9a-f]{64}" | head -1)
        CONTRACT_ADDR=$(echo "$TX_OUTPUT" | grep -oE "contractAddress[[:space:]]+0x[0-9a-fA-F]{40}" | awk '{print $2}' || echo "")
        
        if [ -n "$TX_HASH" ]; then
            echo "Transaction: $TX_HASH"
        fi
        if [ -n "$CONTRACT_ADDR" ]; then
            echo "Contract Address: $CONTRACT_ADDR"
            echo ""
            echo "Waiting 20 seconds for confirmation..."
            sleep 20
            
            CODE=$(cast code "$CONTRACT_ADDR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
            if [ -n "$CODE" ] && [ "$CODE" != "0x" ] && [ ${#CODE} -gt 100 ]; then
                echo "✓✓✓ Contract creation CONFIRMED!"
                echo "✓ Network allows contract creation"
                VALUE=$(cast call "$CONTRACT_ADDR" "value()" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
                if [ -n "$VALUE" ]; then
                    echo "✓ Contract is functional (value: $VALUE)"
                fi
            else
                echo "⚠ Contract not yet confirmed (may take time)"
                echo "Code length: ${#CODE}"
            fi
        else
            echo "⚠ Contract address not in output (check transaction receipt)"
        fi
    elif echo "$TX_OUTPUT" | grep -qi "revert\|error\|denied\|restricted"; then
        echo "✗✗✗ Contract creation may be RESTRICTED!"
        echo ""
        echo "Error output:"
        echo "$TX_OUTPUT" | grep -iE "revert|error|denied|restricted" | head -5
        echo ""
        echo "⚠ Network may have restrictions on contract creation"
    else
        echo "⚠ Deployment attempt unclear"
        echo "Output:"
        echo "$TX_OUTPUT" | tail -10
    fi
else
    echo "✗ Failed to get bytecode"
fi

# Cleanup
rm -rf "$TEMP_DIR"

echo ""
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     SUMMARY                                                  ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "Network Status:"
echo "  Block: $BLOCK"
echo "  Chain ID: $CHAIN_ID"
echo "  Account Balance: $BALANCE_ETH ETH"
echo ""
echo "If contract creation test failed:"
echo "  1. Check network configuration"
echo "  2. Verify CREATE opcode is enabled"
echo "  3. Contact network administrators"
echo ""
