#!/usr/bin/env bash
# Comprehensive Test of LINK Token Contract and Deployment Script
# Tests all components before actual deployment

set -uo pipefail  # Remove -e to allow error handling

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 SUITE                         ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "ChainID: $CHAIN_ID"
echo "RPC: $RPC_URL"
echo ""

# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

PASSED=0
FAILED=0
WARNINGS=0

test_pass() {
    echo -e "${GREEN}✅ PASS:${NC} $1"
    ((PASSED++))
}

test_fail() {
    echo -e "${RED}❌ FAIL:${NC} $1"
    ((FAILED++))
}

test_warn() {
    echo -e "${YELLOW}⚠️  WARN:${NC} $1"
    ((WARNINGS++))
}

echo "═══════════════════════════════════════════════════════════════"
echo "TEST 1: Environment Variables"
echo "═══════════════════════════════════════════════════════════════"
echo ""

if [ -z "${PRIVATE_KEY:-}" ]; then
    test_fail "PRIVATE_KEY not available in effective environment"
else
    test_pass "PRIVATE_KEY is set"
    DEPLOYER=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || echo "")
    if [ -n "$DEPLOYER" ]; then
        test_pass "PRIVATE_KEY is valid (deployer: $DEPLOYER)"
    else
        test_fail "PRIVATE_KEY is invalid"
    fi
fi

if [ -z "${RPC_URL_138:-}" ]; then
    test_warn "RPC_URL_138 not set, using default: $RPC_URL"
else
    test_pass "RPC_URL_138 is set: $RPC_URL"
fi

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "TEST 2: Network Connectivity"
echo "═══════════════════════════════════════════════════════════════"
echo ""

# Test RPC connectivity
if cast block-number --rpc-url "$RPC_URL" > /dev/null 2>&1; then
    BLOCK_NUM=$(cast block-number --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    test_pass "RPC is accessible (block: $BLOCK_NUM)"
else
    test_fail "RPC is not accessible"
fi

# Test chain ID
ACTUAL_CHAIN_ID=$(cast chain-id --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
if [ "$ACTUAL_CHAIN_ID" = "$CHAIN_ID" ]; then
    test_pass "Chain ID matches ($CHAIN_ID)"
else
    test_fail "Chain ID mismatch (expected: $CHAIN_ID, got: $ACTUAL_CHAIN_ID)"
fi

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "TEST 3: Deployer Account"
echo "═══════════════════════════════════════════════════════════════"
echo ""

if [ -z "${DEPLOYER:-}" ]; then
    test_fail "Cannot determine deployer address"
else
    test_pass "Deployer address: $DEPLOYER"
    
    # Check balance
    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")
    
    if (( $(echo "$BALANCE_ETH > 0.1" | bc -l 2>/dev/null || echo 0) )); then
        test_pass "Deployer has sufficient balance: $BALANCE_ETH ETH"
    else
        test_fail "Deployer has insufficient balance: $BALANCE_ETH ETH (need > 0.1 ETH)"
    fi
    
    # Check nonce
    NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    test_pass "Deployer nonce: $NONCE"
fi

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "TEST 4: Contract Source Files"
echo "═══════════════════════════════════════════════════════════════"
echo ""

# Check for MockLinkToken in source project
SOURCE_PROJECT="/home/intlc/projects/smom-dbis-138"
if [ -f "$SOURCE_PROJECT/contracts/tokens/MockLinkToken.sol" ]; then
    test_pass "MockLinkToken.sol found in source project"
    CONTRACT_FILE="$SOURCE_PROJECT/contracts/tokens/MockLinkToken.sol"
else
    test_warn "MockLinkToken.sol not found in source project"
    CONTRACT_FILE=""
fi

# Check for deployment script
if [ -f "$SOURCE_PROJECT/script/DeployMockLinkToken.s.sol" ]; then
    test_pass "DeployMockLinkToken.s.sol found"
    SCRIPT_FILE="$SOURCE_PROJECT/script/DeployMockLinkToken.s.sol"
else
    test_warn "DeployMockLinkToken.s.sol not found"
    SCRIPT_FILE=""
fi

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "TEST 5: Foundry Installation"
echo "═══════════════════════════════════════════════════════════════"
echo ""

if command -v forge &> /dev/null; then
    FORGE_VERSION=$(forge --version 2>/dev/null || echo "unknown")
    test_pass "Foundry is installed ($FORGE_VERSION)"
else
    test_fail "Foundry is not installed"
fi

if command -v cast &> /dev/null; then
    CAST_VERSION=$(cast --version 2>/dev/null || echo "unknown")
    test_pass "Cast is installed ($CAST_VERSION)"
else
    test_fail "Cast is not installed"
fi

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "TEST 6: Contract Compilation"
echo "═══════════════════════════════════════════════════════════════"
echo ""

if [ -n "$CONTRACT_FILE" ] && [ -f "$CONTRACT_FILE" ]; then
    cd "$SOURCE_PROJECT"
    
    if forge build --contracts contracts/tokens/MockLinkToken.sol > /dev/null 2>&1; then
        test_pass "MockLinkToken compiles successfully"
        
        # Check if artifact exists
        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
                test_pass "Contract bytecode generated (${#BYTECODE} chars)"
            else
                test_fail "Contract bytecode is invalid"
            fi
        else
            test_fail "Contract artifact not found"
        fi
    else
        test_fail "MockLinkToken compilation failed"
        echo "   Run: cd $SOURCE_PROJECT && forge build"
    fi
    
    cd "$PROJECT_ROOT"
else
    test_warn "Skipping compilation test (contract file not found)"
fi

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "TEST 7: Deployment Script Validation"
echo "═══════════════════════════════════════════════════════════════"
echo ""

if [ -n "$SCRIPT_FILE" ] && [ -f "$SCRIPT_FILE" ]; then
    test_pass "Deployment script exists"
    
    # Check script syntax
    cd "$SOURCE_PROJECT"
    if forge script script/DeployMockLinkToken.s.sol:DeployMockLinkToken --dry-run > /dev/null 2>&1; then
        test_pass "Deployment script syntax is valid"
    else
        test_warn "Deployment script dry-run failed (may need environment)"
    fi
    cd "$PROJECT_ROOT"
else
    test_warn "Deployment script not found"
fi

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "TEST 8: Existing LINK Token Check"
echo "═══════════════════════════════════════════════════════════════"
echo ""

if [ -n "${LINK_TOKEN:-}" ] && [ "$LINK_TOKEN" != "" ]; then
    test_pass "LINK_TOKEN is configured: $LINK_TOKEN"
    
    # Check if contract exists
    CODE=$(cast code "$LINK_TOKEN" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    if [ -n "$CODE" ] && [ "$CODE" != "0x" ] && [ ${#CODE} -gt 100 ]; then
        test_pass "LINK token contract exists on-chain (${#CODE} chars)"
        
        # Try to call contract functions
        NAME=$(cast call "$LINK_TOKEN" "name()(string)" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
        SYMBOL=$(cast call "$LINK_TOKEN" "symbol()(string)" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
        
        if [ -n "$NAME" ] && [ -n "$SYMBOL" ]; then
            test_pass "LINK token is valid ERC20 (Name: $NAME, Symbol: $SYMBOL)"
        else
            test_warn "LINK token exists but may not be valid ERC20"
        fi
    else
        test_warn "LINK token address configured but contract not found on-chain"
    fi
else
    test_warn "LINK_TOKEN not configured in address inventory"
fi

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "TEST 9: Gas Estimation"
echo "═══════════════════════════════════════════════════════════════"
echo ""

if [ -n "$CONTRACT_FILE" ] && [ -f "$CONTRACT_FILE" ]; then
    cd "$SOURCE_PROJECT"
    
    # Try to estimate gas (this may fail if network doesn't support it)
    GAS_PRICE=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    if [ "$GAS_PRICE" != "0" ]; then
        GAS_PRICE_GWEI=$(echo "scale=2; $GAS_PRICE / 1000000000" | bc 2>/dev/null || echo "0")
        test_pass "Current gas price: $GAS_PRICE_GWEI gwei"
    else
        test_warn "Could not fetch gas price"
    fi
    
    cd "$PROJECT_ROOT"
else
    test_warn "Skipping gas estimation (contract not available)"
fi

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "TEST 10: Deployment Scripts Availability"
echo "═══════════════════════════════════════════════════════════════"
echo ""

DEPLOY_SCRIPTS=(
    "scripts/force-deploy-link.sh"
    "scripts/deploy-link-token.sh"
    "scripts/deploy-via-rpc-json.sh"
)

for script in "${DEPLOY_SCRIPTS[@]}"; do
    if [ -f "$PROJECT_ROOT/$script" ]; then
        if [ -x "$PROJECT_ROOT/$script" ]; then
            test_pass "$script exists and is executable"
        else
            test_warn "$script exists but not executable"
        fi
    else
        test_warn "$script not found"
    fi
done

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "TEST SUMMARY"
echo "═══════════════════════════════════════════════════════════════"
echo ""
echo -e "${GREEN}Passed:${NC} $PASSED"
echo -e "${RED}Failed:${NC} $FAILED"
echo -e "${YELLOW}Warnings:${NC} $WARNINGS"
echo ""

if [ $FAILED -eq 0 ]; then
    echo -e "${GREEN}✅ All critical tests passed! Ready for deployment.${NC}"
    echo ""
    echo "To deploy LINK token, run:"
    echo "  ./scripts/force-deploy-link.sh [GAS_PRICE]"
    echo ""
    echo "Or use the source project deployment script:"
    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"
    exit 0
else
    echo -e "${RED}❌ Some critical tests failed. Please fix issues before deploying.${NC}"
    exit 1
fi
