#!/usr/bin/env bash
# Simplified Test of LINK Token Contract and Deployment Script

set -uo pipefail

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

load_explorer_runtime_env

RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
CHAIN_ID=138
LINK_TOKEN="${LINK_TOKEN:-$(resolve_address_value LINK_TOKEN LINK_TOKEN "")}"

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║     LINK TOKEN DEPLOYMENT TEST                               ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""

# Test 1: Environment
echo "1. Environment Variables:"
if [ -z "${PRIVATE_KEY:-}" ]; then
    echo "   ❌ PRIVATE_KEY not available in effective environment"
    exit 1
else
    DEPLOYER=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || echo "")
    if [ -z "$DEPLOYER" ]; then
        echo "   ❌ PRIVATE_KEY invalid"
        exit 1
    else
        echo "   ✅ PRIVATE_KEY valid (deployer: $DEPLOYER)"
    fi
fi
echo "   ✅ RPC_URL: $RPC_URL"
echo ""

# Test 2: Network
echo "2. Network Connectivity:"
if ! cast block-number --rpc-url "$RPC_URL" > /dev/null 2>&1; then
    echo "   ❌ RPC not accessible"
    exit 1
fi
BLOCK_NUM=$(cast block-number --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
echo "   ✅ RPC accessible (block: $BLOCK_NUM)"

ACTUAL_CHAIN_ID=$(cast chain-id --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
if [ "$ACTUAL_CHAIN_ID" != "$CHAIN_ID" ]; then
    echo "   ❌ Chain ID mismatch (expected: $CHAIN_ID, got: $ACTUAL_CHAIN_ID)"
    exit 1
fi
echo "   ✅ Chain ID matches ($CHAIN_ID)"
echo ""

# Test 3: Deployer Account
echo "3. Deployer Account:"
BALANCE=$(cast balance "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
BALANCE_ETH=$(echo "scale=4; $BALANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")
# Check if balance > 0.1 ETH
if (( $(echo "$BALANCE_ETH > 0.1" | bc -l 2>/dev/null || echo 0) )); then
    echo "   ✅ Balance sufficient: $BALANCE_ETH ETH"
else
    echo "   ⚠️  Balance: $BALANCE_ETH ETH (may be sufficient for deployment)"
    # Don't exit - deployment might still work with lower balance
fi

NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
echo "   ✅ Nonce: $NONCE"
echo ""

# Test 4: Contract Files
echo "4. Contract Files:"
SOURCE_PROJECT="/home/intlc/projects/smom-dbis-138"
if [ -f "$SOURCE_PROJECT/contracts/tokens/MockLinkToken.sol" ]; then
    echo "   ✅ MockLinkToken.sol found"
    CONTRACT_FILE="$SOURCE_PROJECT/contracts/tokens/MockLinkToken.sol"
else
    echo "   ⚠️  MockLinkToken.sol not found in source project"
    CONTRACT_FILE=""
fi

if [ -f "$SOURCE_PROJECT/script/DeployMockLinkToken.s.sol" ]; then
    echo "   ✅ DeployMockLinkToken.s.sol found"
else
    echo "   ⚠️  DeployMockLinkToken.s.sol not found"
fi
echo ""

# Test 5: Foundry
echo "5. Foundry Installation:"
if ! command -v forge &> /dev/null; then
    echo "   ❌ Foundry not installed"
    exit 1
fi
echo "   ✅ Foundry installed"

if ! command -v cast &> /dev/null; then
    echo "   ❌ Cast not installed"
    exit 1
fi
echo "   ✅ Cast installed"
echo ""

# Test 6: Compilation
echo "6. Contract Compilation:"
if [ -n "$CONTRACT_FILE" ] && [ -f "$CONTRACT_FILE" ]; then
    cd "$SOURCE_PROJECT"
    if forge build --contracts contracts/tokens/MockLinkToken.sol > /dev/null 2>&1; then
        echo "   ✅ MockLinkToken compiles successfully"
        
        ARTIFACT="$SOURCE_PROJECT/out/MockLinkToken.sol/MockLinkToken.json"
        if [ -f "$ARTIFACT" ]; then
            BYTECODE=$(jq -r '.bytecode.object' "$ARTIFACT" 2>/dev/null || echo "")
            if [ -n "$BYTECODE" ] && [ "$BYTECODE" != "null" ] && [ ${#BYTECODE} -gt 100 ]; then
                echo "   ✅ Bytecode generated (${#BYTECODE} chars)"
            else
                echo "   ❌ Bytecode invalid"
            fi
        fi
    else
        echo "   ❌ Compilation failed"
    fi
    cd "$PROJECT_ROOT"
else
    echo "   ⚠️  Skipping (contract file not found)"
fi
echo ""

# Test 7: Existing LINK Token
echo "7. Existing LINK Token:"
if [ -n "${LINK_TOKEN:-}" ] && [ "$LINK_TOKEN" != "" ]; then
    CODE=$(cast code "$LINK_TOKEN" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    if [ -n "$CODE" ] && [ "$CODE" != "0x" ] && [ ${#CODE} -gt 100 ]; then
        echo "   ✅ LINK token exists on-chain: $LINK_TOKEN"
        NAME=$(cast call "$LINK_TOKEN" "name()(string)" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
        if [ -n "$NAME" ]; then
            echo "   ✅ Token name: $NAME"
        fi
    else
        echo "   ⚠️  LINK_TOKEN configured but not found on-chain: $LINK_TOKEN"
    fi
else
    echo "   ⚠️  LINK_TOKEN not configured in address inventory"
fi
echo ""

echo "═══════════════════════════════════════════════════════════════"
echo "✅ All tests passed! Ready for deployment."
echo ""
echo "To deploy LINK token:"
echo "  cd /home/intlc/projects/smom-dbis-138"
echo "  forge script script/DeployMockLinkToken.s.sol:DeployMockLinkToken \\"
echo "    --rpc-url $RPC_URL \\"
echo "    --broadcast \\"
echo "    --legacy \\"
echo "    --gas-price 20000000000"
echo ""
