#!/usr/bin/env bash
# Complete Chain-138 deployment script

set -e

cd "$(dirname "$0")/../.."

# Color codes

echo "==================================================================="
echo "  CHAIN-138 COMPLETE DEPLOYMENT"
echo "==================================================================="

# Load environment variables
if [ -f .env ]; then
    source .env 2>/dev/null || true
fi

ERRORS=0

# Step 1: Configure .env
log_info "Step 1: Configuring .env for Chain-138"

if [ -z "$CHAIN138_RPC_URL" ] || [ "$CHAIN138_RPC_URL" = "" ]; then
    log_warn "⚠️  CHAIN138_RPC_URL not configured"
    echo "  Adding default RPC URL to .env..."
    
    if ! grep -q "CHAIN138_RPC_URL" .env 2>/dev/null; then
        echo "" >> .env
        echo "# Chain-138 Configuration" >> .env
        echo "CHAIN138_RPC_URL=https://rpc.d-bis.org" >> .env
        echo "CHAIN138_SELECTOR=0x000000000000008a" >> .env
        log_success "✅ Added CHAIN138_RPC_URL to .env"
    fi
else
    log_success "✅ CHAIN138_RPC_URL already configured"
fi

# Step 2: Generate genesis if needed
log_info "Step 2: Checking genesis file"

if [ ! -f "genesis.json" ]; then
    if [ -f "scripts/generate-genesis.sh" ]; then
        log_warn "⚠️  genesis.json not found, generating..."
        ./scripts/generate-genesis.sh
        if [ -f "genesis.json" ]; then
            log_success "✅ genesis.json generated"
        else
            log_error "❌ Failed to generate genesis.json"
            ERRORS=$((ERRORS + 1))
        fi
    else
        log_error "❌ genesis.json not found and generate-genesis.sh not available"
        ERRORS=$((ERRORS + 1))
    fi
else
    log_success "✅ genesis.json exists"
    
    # Verify WETH9/WETH10 in genesis
    if grep -q "C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" genesis.json 2>/dev/null; then
        log_success "✅ WETH9 found in genesis.json"
    else
        log_warn "⚠️  WETH9 not found in genesis.json"
    fi
    
    if grep -q "f4BB2e28688e89fCcE3c0580D37d36A7672E8A9f" genesis.json 2>/dev/null; then
        log_success "✅ WETH10 found in genesis.json"
    else
        log_warn "⚠️  WETH10 not found in genesis.json"
    fi
fi

# Step 3: Check infrastructure deployment
log_info "Step 3: Checking infrastructure deployment"

if command -v kubectl &> /dev/null && kubectl cluster-info &> /dev/null 2>&1; then
    log_success "✅ Kubernetes cluster accessible"
    
    # Check for besu-network namespace
    if kubectl get namespace besu-network &> /dev/null; then
        log_success "✅ besu-network namespace exists"
        
        POD_COUNT=$(kubectl get pods -n besu-network 2>/dev/null | grep -v NAME | wc -l)
        if [ "$POD_COUNT" -gt 0 ]; then
            log_success "✅ $POD_COUNT pods running in besu-network"
        else
            log_warn "⚠️  No pods found in besu-network namespace"
            echo "  Run: kubectl apply -k k8s/base"
        fi
    else
        log_warn "⚠️  besu-network namespace not found"
        echo "  Run: kubectl create namespace besu-network"
    fi
else
    log_warn "⚠️  Kubernetes cluster not accessible"
    echo "  Infrastructure deployment may be required"
fi

# Step 4: Test RPC connectivity
log_info "Step 4: Testing RPC connectivity"

if [ -n "$CHAIN138_RPC_URL" ] && [ "$CHAIN138_RPC_URL" != "" ]; then
    echo -n "  Testing $CHAIN138_RPC_URL: "
    if curl -s --max-time 10 "$CHAIN138_RPC_URL" -X POST -H "Content-Type: application/json" \
        -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' 2>/dev/null | grep -q "result"; then
        log_success "✅ Accessible"
        
        # Get chain ID
        CHAIN_ID=$(curl -s --max-time 10 "$CHAIN138_RPC_URL" -X POST -H "Content-Type: application/json" \
            -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' 2>/dev/null | \
            python3 -c "import sys, json; print(int(json.load(sys.stdin).get('result', '0x0'), 16))" 2>/dev/null || echo "0")
        
        if [ "$CHAIN_ID" = "138" ]; then
            echo -e "  ${GREEN}✅ Chain ID: 138 (correct)${NC}"
        else
            echo -e "  ${YELLOW}⚠️  Chain ID: $CHAIN_ID (expected 138)${NC}"
        fi
    else
        log_error "❌ Not accessible"
        ERRORS=$((ERRORS + 1))
    fi
else
    log_error "❌ CHAIN138_RPC_URL not configured"
    ERRORS=$((ERRORS + 1))
fi

# Step 5: Verify historical CCIPTxReporter
log_info "Step 5: Checking CCIPTxReporter"

if [ -z "$CHAIN138_CCIP_REPORTER" ] || [ "$CHAIN138_CCIP_REPORTER" = "" ]; then
    log_warn "⚠️  CCIPTxReporter not configured"
    echo "  Historical source archive:"
    echo "    archive/solidity/contracts/ccip-integration/CCIPTxReporter.sol"
    echo "  If you still rely on this flow, set CHAIN138_CCIP_REPORTER to the deployed address."
    echo "  Restore the archived source before attempting a fresh redeploy."
else
    log_success "✅ CCIPTxReporter address: $CHAIN138_CCIP_REPORTER"
    
    # Verify on-chain
    if [ -n "$CHAIN138_RPC_URL" ] && command -v cast &> /dev/null; then
        REPORTER_CODE=$(cast code "$CHAIN138_CCIP_REPORTER" --rpc-url "$CHAIN138_RPC_URL" 2>/dev/null || echo "")
        if [ -n "$REPORTER_CODE" ] && [ "$REPORTER_CODE" != "0x" ] && [ ${#REPORTER_CODE} -gt 2 ]; then
            echo -e "  ${GREEN}✅ Verified on-chain${NC}"
        else
            echo -e "  ${RED}❌ Not found on-chain${NC}"
        fi
    fi
fi

# Step 6: Verify predeployed contracts
log_info "Step 6: Verifying predeployed contracts"

WETH9_ADDR="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
WETH10_ADDR="0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"

if [ -n "$CHAIN138_RPC_URL" ] && command -v cast &> /dev/null; then
    echo -n "  Checking WETH9: "
    WETH9_CODE=$(cast code "$WETH9_ADDR" --rpc-url "$CHAIN138_RPC_URL" 2>/dev/null || echo "")
    if [ -n "$WETH9_CODE" ] && [ "$WETH9_CODE" != "0x" ] && [ ${#WETH9_CODE} -gt 2 ]; then
        log_success "✅ Deployed"
    else
        log_warn "⚠️  Not found (may need genesis predeployment)"
    fi
    
    echo -n "  Checking WETH10: "
    WETH10_CODE=$(cast code "$WETH10_ADDR" --rpc-url "$CHAIN138_RPC_URL" 2>/dev/null || echo "")
    if [ -n "$WETH10_CODE" ] && [ "$WETH10_CODE" != "0x" ] && [ ${#WETH10_CODE} -gt 2 ]; then
        log_success "✅ Deployed"
    else
        log_warn "⚠️  Not found (may need genesis predeployment)"
    fi
else
    log_warn "⚠️  Cannot verify (RPC or cast not available)"
fi

# Step 7: Run verification
log_info "Step 7: Running verification"

if [ -f "scripts/deployment/verify-chain138-complete.sh" ]; then
    ./scripts/deployment/verify-chain138-complete.sh
    VERIFY_STATUS=$?
else
    log_warn "⚠️  Verification script not found"
    VERIFY_STATUS=1
fi

echo "==================================================================="
log_info "DEPLOYMENT SUMMARY"
echo "==================================================================="

if [ $ERRORS -eq 0 ] && [ $VERIFY_STATUS -eq 0 ]; then
    log_success "✅ Chain-138 deployment complete!"
    exit 0
elif [ $ERRORS -eq 0 ]; then
    log_warn "⚠️  Deployment in progress, some verification warnings"
    exit 0
else
    log_error "❌ Deployment has errors that need to be addressed"
    echo "  Errors: $ERRORS"
    exit 1
fi
