#!/usr/bin/env bash
# Verify .env file configuration
# Checks that all required environment variables are set

set -euo pipefail


SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# 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
ENV_FILE="${PROJECT_ROOT}/.env"

# Load .env file if it exists
if [ -f "$ENV_FILE" ]; then
    set -a
    source "$ENV_FILE"
    set +a
fi

log() {
    log_success "[✓] $1"
}

error() {
    log_error "[✗] $1"
}

warn() {
    log_warn "[!] $1"
}

info() {
    log_info "[i] $1"
}

log_info "=== Environment Variables Verification ==="
echo

# Check if .env file exists
if [ ! -f "$ENV_FILE" ]; then
    error ".env file not found at: $ENV_FILE"
    exit 1
fi

log ".env file found: $ENV_FILE"
echo

# Azure Configuration
log_info "Azure Configuration:"
if [ -n "${AZURE_SUBSCRIPTION_ID:-}" ]; then
    log "AZURE_SUBSCRIPTION_ID is set: ${AZURE_SUBSCRIPTION_ID:0:8}..."
else
    error "AZURE_SUBSCRIPTION_ID is not set"
fi

if [ -n "${AZURE_TENANT_ID:-}" ]; then
    log "AZURE_TENANT_ID is set: ${AZURE_TENANT_ID:0:8}..."
else
    warn "AZURE_TENANT_ID is not set (optional for service principal)"
fi

if [ -n "${AZURE_RESOURCE_GROUP:-}" ]; then
    log "AZURE_RESOURCE_GROUP is set: $AZURE_RESOURCE_GROUP"
else
    warn "AZURE_RESOURCE_GROUP is not set (will use default: defi-oracle-mainnet-rg)"
fi

if [ -n "${AZURE_LOCATION:-}" ]; then
    log "AZURE_LOCATION is set: $AZURE_LOCATION"
else
    warn "AZURE_LOCATION is not set (will use default: westeurope)"
fi

echo

# Terraform Backend
log_info "Terraform Backend Configuration:"
if [ -n "${ARM_STORAGE_ACCOUNT_NAME:-}" ]; then
    log "ARM_STORAGE_ACCOUNT_NAME is set: $ARM_STORAGE_ACCOUNT_NAME"
else
    warn "ARM_STORAGE_ACCOUNT_NAME is not set"
fi

if [ -n "${ARM_RESOURCE_GROUP_NAME:-}" ]; then
    log "ARM_RESOURCE_GROUP_NAME is set: $ARM_RESOURCE_GROUP_NAME"
else
    warn "ARM_RESOURCE_GROUP_NAME is not set (will use default: tfstate-rg)"
fi

if [ -n "${ARM_CONTAINER_NAME:-}" ]; then
    log "ARM_CONTAINER_NAME is set: $ARM_CONTAINER_NAME"
else
    warn "ARM_CONTAINER_NAME is not set (will use default: tfstate)"
fi

if [ -n "${ARM_ACCESS_KEY:-}" ]; then
    log "ARM_ACCESS_KEY is set: ${ARM_ACCESS_KEY:0:8}..."
else
    warn "ARM_ACCESS_KEY is not set"
fi

echo

# Cloudflare Configuration
log_info "Cloudflare Configuration:"
if [ -n "${CLOUDFLARE_ZONE_ID:-}" ]; then
    log "CLOUDFLARE_ZONE_ID is set: $CLOUDFLARE_ZONE_ID"
    
    # Test API token if both are set
    if [ -n "${CLOUDFLARE_API_TOKEN:-}" ]; then
        log "CLOUDFLARE_API_TOKEN is set: ${CLOUDFLARE_API_TOKEN:0:8}..."
        
        # Test the token
        info "Testing Cloudflare API token..."
        TEST_RESPONSE=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$CLOUDFLARE_ZONE_ID" \
            -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
            -H "Content-Type: application/json" 2>/dev/null || echo "")
        
        if echo "$TEST_RESPONSE" | grep -q '"success":true' 2>/dev/null; then
            ZONE_NAME=$(echo "$TEST_RESPONSE" | grep -o '"name":"[^"]*"' | cut -d'"' -f4 || echo "unknown")
            log "Cloudflare API token is valid! Zone: $ZONE_NAME"
        else
            error "Cloudflare API token test failed"
            error "Response: $(echo "$TEST_RESPONSE" | head -c 200)"
        fi
    else
        error "CLOUDFLARE_API_TOKEN is not set"
    fi
else
    error "CLOUDFLARE_ZONE_ID is not set"
fi

echo

# Optional Configuration
log_info "Optional Configuration:"
if [ -n "${AZURE_CLIENT_ID:-}" ]; then
    log "AZURE_CLIENT_ID is set (service principal)"
else
    info "AZURE_CLIENT_ID not set (using interactive login)"
fi

if [ -n "${RPC_URL:-}" ]; then
    log "RPC_URL is set: $RPC_URL"
else
    info "RPC_URL not set (will be set after deployment)"
fi

if [ -n "${EXPLORER_URL:-}" ]; then
    log "EXPLORER_URL is set: $EXPLORER_URL"
else
    info "EXPLORER_URL not set (will be set after deployment)"
fi

if [ -n "${PRIVATE_KEY:-}" ]; then
    log "PRIVATE_KEY is set: ${PRIVATE_KEY:0:10}..."
else
    info "PRIVATE_KEY not set (needed for contract deployment)"
fi

echo
log_info "=== Verification Complete ==="

# Summary
echo
MISSING_CRITICAL=0
MISSING_OPTIONAL=0

[ -z "${AZURE_SUBSCRIPTION_ID:-}" ] && MISSING_CRITICAL=$((MISSING_CRITICAL + 1))
[ -z "${CLOUDFLARE_ZONE_ID:-}" ] && MISSING_CRITICAL=$((MISSING_CRITICAL + 1))
[ -z "${CLOUDFLARE_API_TOKEN:-}" ] && MISSING_CRITICAL=$((MISSING_CRITICAL + 1))

[ -z "${ARM_STORAGE_ACCOUNT_NAME:-}" ] && MISSING_OPTIONAL=$((MISSING_OPTIONAL + 1))
[ -z "${ARM_ACCESS_KEY:-}" ] && MISSING_OPTIONAL=$((MISSING_OPTIONAL + 1))

if [ $MISSING_CRITICAL -eq 0 ]; then
    log "All critical variables are set!"
    if [ $MISSING_OPTIONAL -gt 0 ]; then
        warn "$MISSING_OPTIONAL optional variable(s) missing (Terraform backend)"
        info "Run: ./scripts/deployment/populate-env.sh to set up Terraform backend"
    fi
else
    error "$MISSING_CRITICAL critical variable(s) missing"
    info "Run: ./scripts/deployment/populate-env.sh to complete setup"
    exit 1
fi

