#!/bin/bash

# Check for PRIVATE_KEY in .env file
# This script checks if .env exists and if PRIVATE_KEY is set

set -e

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

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

echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║     PRIVATE_KEY Environment Check                           ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""

cd "$PROJECT_ROOT"

# Check 1: .env file existence
echo -e "${YELLOW}1. Checking for .env file...${NC}"
if [ -f .env ]; then
    echo -e "${GREEN}✅ .env file exists${NC}"
    ENV_EXISTS=true
else
    echo -e "${RED}❌ .env file does not exist${NC}"
    ENV_EXISTS=false
fi
echo ""

# Check 2: PRIVATE_KEY in .env
if [ "$ENV_EXISTS" = true ]; then
    echo -e "${YELLOW}2. Checking for PRIVATE_KEY in .env...${NC}"
    if grep -q "^PRIVATE_KEY=" .env 2>/dev/null; then
        PRIVATE_KEY_LINE=$(grep "^PRIVATE_KEY=" .env | head -1)
        PRIVATE_KEY_VALUE=$(echo "$PRIVATE_KEY_LINE" | cut -d'=' -f2-)
        
        # Check if it's empty or just whitespace
        if [ -z "${PRIVATE_KEY_VALUE// }" ]; then
            echo -e "${RED}❌ PRIVATE_KEY is set but empty in .env${NC}"
            PRIVATE_KEY_SET=false
        else
            echo -e "${GREEN}✅ PRIVATE_KEY is set in .env${NC}"
            PRIVATE_KEY_SET=true
            
            # Show first few characters for verification (without exposing full key)
            KEY_PREFIX=$(echo "$PRIVATE_KEY_VALUE" | cut -c1-10)
            KEY_LENGTH=${#PRIVATE_KEY_VALUE}
            echo "   Key prefix: ${KEY_PREFIX}... (length: $KEY_LENGTH chars)"
            
            # Validate format
            if [[ "$PRIVATE_KEY_VALUE" =~ ^0x[0-9a-fA-F]{64}$ ]] || [[ "$PRIVATE_KEY_VALUE" =~ ^[0-9a-fA-F]{64}$ ]]; then
                echo -e "${GREEN}   ✅ Format appears valid (64 hex chars)${NC}"
            else
                echo -e "${YELLOW}   ⚠️  Format may be invalid (expected 64 hex chars, with or without 0x prefix)${NC}"
            fi
        fi
    else
        echo -e "${RED}❌ PRIVATE_KEY is NOT set in .env${NC}"
        PRIVATE_KEY_SET=false
    fi
    echo ""
fi

# Check 3: PRIVATE_KEY in environment
echo -e "${YELLOW}3. Checking for PRIVATE_KEY in environment...${NC}"
if [ -z "$PRIVATE_KEY" ]; then
    echo -e "${RED}❌ PRIVATE_KEY is not set in environment${NC}"
    ENV_VAR_SET=false
else
    echo -e "${GREEN}✅ PRIVATE_KEY is set in environment${NC}"
    ENV_VAR_SET=true
    
    # Try to get deployer address
    DEPLOYER=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || echo "")
    if [ -z "$DEPLOYER" ]; then
        echo -e "${RED}   ❌ Invalid PRIVATE_KEY format (cannot derive address)${NC}"
    else
        echo -e "${GREEN}   ✅ PRIVATE_KEY is valid${NC}"
        echo "   Deployer address: $DEPLOYER"
        
        # Check balance if RPC is available
        RPC_URL=${RPC_URL:-${RPC_URL_138:-"http://192.168.11.250:8545"}}
        BALANCE=$(cast balance "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
        if [ "$BALANCE" != "0" ]; then
            BALANCE_ETH=$(echo "scale=4; $BALANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")
            echo "   Balance: $BALANCE_ETH ETH"
        else
            echo -e "${YELLOW}   ⚠️  Could not check balance (RPC may be unavailable)${NC}"
        fi
    fi
fi
echo ""

# Summary
echo -e "${BLUE}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║     Summary                                                  ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""

if [ "$ENV_VAR_SET" = true ]; then
    echo -e "${GREEN}✅ PRIVATE_KEY is available in environment${NC}"
    echo "   You can proceed with deployment"
elif [ "$PRIVATE_KEY_SET" = true ]; then
    echo -e "${YELLOW}⚠️  PRIVATE_KEY is in .env but not loaded in environment${NC}"
    echo "   Run: source .env"
    echo "   Or: export PRIVATE_KEY=\$(grep '^PRIVATE_KEY=' .env | cut -d'=' -f2-)"
else
    echo -e "${RED}❌ PRIVATE_KEY is not set${NC}"
    echo ""
    echo "To set PRIVATE_KEY:"
    echo "  1. Create .env file:"
    echo "     echo 'PRIVATE_KEY=<your_private_key>' > .env"
    echo ""
    echo "  2. Or export directly:"
    echo "     export PRIVATE_KEY=<your_private_key>"
    echo ""
    echo "  3. Then run deployment:"
    echo "     ./scripts/deploy-and-integrate-all.sh"
fi
echo ""

