#!/usr/bin/env bash

# Check Deployment Status
# This script checks the current deployment status and identifies the last completed step

set -e


# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi

log_info "=== Deployment Status Check ==="

# Check .env file
if [ ! -f .env ]; then
    log_error "❌ .env file not found"
    echo "Please create .env file with required variables"
    exit 1
fi

log_success "✅ .env file exists"

# Load environment variables
source .env

# Check RPC endpoint
if [ -z "$RPC_URL" ]; then
    log_error "❌ RPC_URL not set in .env"
    echo "Please set RPC_URL in .env file"
else
    log_success "✅ RPC_URL configured: ${RPC_URL}"
    
    # Test RPC endpoint
    log_warn "Testing RPC endpoint..."
    if curl -s -X POST "$RPC_URL" -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' > /dev/null 2>&1; then
        log_success "✅ RPC endpoint is accessible"
        
        # Get chain ID
        CHAIN_ID=$(curl -s -X POST "$RPC_URL" -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' | grep -oE '"result":"0x[0-9a-fA-F]+"' | cut -d'"' -f4 | xargs -I {} echo "ibase=16; {}" | bc 2>/dev/null || echo "unknown")
        log_success "✅ Chain ID: ${CHAIN_ID}"
        
        # Get latest block
        LATEST_BLOCK=$(curl -s -X POST "$RPC_URL" -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' | grep -oE '"result":"0x[0-9a-fA-F]+"' | cut -d'"' -f4 | xargs -I {} echo "ibase=16; {}" | bc 2>/dev/null || echo "unknown")
        log_success "✅ Latest Block: ${LATEST_BLOCK}"
    else
        log_error "❌ RPC endpoint is not accessible"
        echo "Please ensure the blockchain is deployed and RPC endpoint is accessible"
    fi
fi

# Check PRIVATE_KEY
if [ -z "$PRIVATE_KEY" ]; then
    log_error "❌ PRIVATE_KEY not set in .env"
    echo "Please set PRIVATE_KEY in .env file"
else
    log_success "✅ PRIVATE_KEY configured"
fi

# Check contract addresses
log_info "=== Contract Deployment Status ==="

# CCIP Router
if [ -z "$CCIP_ROUTER" ] || [ "$CCIP_ROUTER" = "0x0000000000000000000000000000000000000000" ]; then
    log_warn "⏳ CCIP_ROUTER: Not deployed"
else
    log_success "✅ CCIP_ROUTER: ${CCIP_ROUTER}"
    
    # Verify contract exists
    if [ -n "$RPC_URL" ]; then
        CODE=$(curl -s -X POST "$RPC_URL" -H "Content-Type: application/json" -d "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getCode\",\"params\":[\"${CCIP_ROUTER}\",\"latest\"],\"id\":1}" | grep -oE '"result":"0x[0-9a-fA-F]*"' | cut -d'"' -f4)
        if [ -n "$CODE" ] && [ "$CODE" != "0x" ]; then
            log_success "   Contract verified on chain"
        else
            log_error "   Contract not found on chain"
        fi
    fi
fi

# CCIP Fee Token
if [ -z "$CCIP_FEE_TOKEN" ] || [ "$CCIP_FEE_TOKEN" = "0x0000000000000000000000000000000000000000" ]; then
    log_warn "⏳ CCIP_FEE_TOKEN: Not configured (using native token)"
else
    log_success "✅ CCIP_FEE_TOKEN: ${CCIP_FEE_TOKEN}"
fi

# WETH9
if [ -z "$WETH9_ADDRESS" ] || [ "$WETH9_ADDRESS" = "0x0000000000000000000000000000000000000000" ]; then
    log_warn "⏳ WETH9_ADDRESS: Not deployed"
else
    log_success "✅ WETH9_ADDRESS: ${WETH9_ADDRESS}"
fi

# WETH10
if [ -z "$WETH10_ADDRESS" ] || [ "$WETH10_ADDRESS" = "0x0000000000000000000000000000000000000000" ]; then
    log_warn "⏳ WETH10_ADDRESS: Not deployed"
else
    log_success "✅ WETH10_ADDRESS: ${WETH10_ADDRESS}"
fi

# CCIPWETH9Bridge
if [ -z "$CCIPWETH9BRIDGE_ADDRESS" ] || [ "$CCIPWETH9BRIDGE_ADDRESS" = "0x0000000000000000000000000000000000000000" ]; then
    log_warn "⏳ CCIPWETH9BRIDGE_ADDRESS: Not deployed"
else
    log_success "✅ CCIPWETH9BRIDGE_ADDRESS: ${CCIPWETH9BRIDGE_ADDRESS}"
fi

# CCIPWETH10Bridge
if [ -z "$CCIPWETH10BRIDGE_ADDRESS" ] || [ "$CCIPWETH10BRIDGE_ADDRESS" = "0x0000000000000000000000000000000000000000" ]; then
    log_warn "⏳ CCIPWETH10BRIDGE_ADDRESS: Not deployed"
else
    log_success "✅ CCIPWETH10BRIDGE_ADDRESS: ${CCIPWETH10BRIDGE_ADDRESS}"
fi

# Oracle Aggregator
if [ -z "$ORACLE_AGGREGATOR_ADDRESS" ] || [ "$ORACLE_AGGREGATOR_ADDRESS" = "0x0000000000000000000000000000000000000000" ]; then
    log_warn "⏳ ORACLE_AGGREGATOR_ADDRESS: Not deployed"
else
    log_success "✅ ORACLE_AGGREGATOR_ADDRESS: ${ORACLE_AGGREGATOR_ADDRESS}"
fi

# Check Terraform status
log_info "=== Infrastructure Status ==="
if [ -d "terraform" ] && [ -f "terraform/terraform.tfstate" ]; then
    log_success "✅ Terraform state file exists"
    cd terraform
    if terraform show > /dev/null 2>&1; then
        log_success "✅ Terraform state is valid"
        
        # Check if AKS cluster exists
        if terraform output -json aks_cluster_name > /dev/null 2>&1; then
            AKS_CLUSTER=$(terraform output -raw aks_cluster_name 2>/dev/null || echo "")
            AKS_RG=$(terraform output -raw aks_resource_group 2>/dev/null || echo "")
            if [ -n "$AKS_CLUSTER" ] && [ -n "$AKS_RG" ]; then
                log_success "✅ AKS Cluster: ${AKS_CLUSTER} in ${AKS_RG}"
            fi
        fi
    else
        log_warn "⏳ Terraform state exists but may be empty"
    fi
    cd ..
else
    log_warn "⏳ Terraform state not found (infrastructure not deployed)"
fi

# Summary
log_info "=== Summary ==="
echo "Ready for contract deployment:"
if [ -n "$RPC_URL" ] && [ -n "$PRIVATE_KEY" ]; then
    log_success "✅ Prerequisites met"
    echo "Run: ./scripts/deployment/deploy-contracts-ordered.sh"
else
    log_error "❌ Prerequisites not met"
    echo "Please configure RPC_URL and PRIVATE_KEY in .env"
fi

