#!/usr/bin/env bash

set -e

# Comprehensive Key Vault management script
# Handles deployment, verification, permission grants, and secret storage

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
load_env --file "$PROJECT_ROOT/.env" ${ENV_PROFILE:+--profile "$ENV_PROFILE"}
SCRIPT_NAME="manage-keyvaults.sh"
SCRIPT_DESC="Manage Key Vault lifecycle: deploy, status, permissions, store-keys, verify, list, complete"
SCRIPT_USAGE="${SCRIPT_NAME} [deploy|status|permissions|store-keys|verify|list|complete] [--dry-run] [--region <name>] [--help]"
SCRIPT_OPTIONS="--dry-run         Do not execute changes\n--region <name>   Limit to a specific region\n--help            Show usage"
SCRIPT_REQUIREMENTS="Azure CLI (ensure_azure_cli), permissions to manage Key Vaults"
handle_help "${1:-}"

# Initialize
SUBSCRIPTION_ID="$(get_subscription_id)"
ensure_azure_cli || exit 1
set_subscription "$SUBSCRIPTION_ID" || true

# Functions
show_help() {
    cat << EOF
Key Vault Management Script

Usage: $0 [COMMAND] [OPTIONS]

Commands:
  deploy           - Deploy all Key Vaults (Phase 1)
  status           - Check Key Vault deployment status
  permissions      - Grant permissions to all Key Vaults
  store-keys       - Store validator node keys in Key Vaults
  verify           - Verify Key Vault configuration
  list             - List all Key Vaults and their secrets count
  complete         - Run all steps: deploy, permissions, store-keys

Options:
  --dry-run        - Show what would be done without executing
  --region REGION  - Process specific region only
  --help           - Show this help message

Examples:
  $0 deploy                      # Deploy all Key Vaults
  $0 status                      # Check status
  $0 complete                    # Run all steps
  $0 store-keys --dry-run        # Preview secret storage
  $0 permissions                 # Grant permissions

EOF
}

deploy_keyvaults() {
    log_info "Deploying Key Vaults..."
    bash "$PROJECT_ROOT/scripts/deployment/deploy-keyvaults-only.sh"
}

check_status() {
    log_info "Checking Key Vault status..."
    bash "$SCRIPT_DIR/check-keyvault-status.sh"
}

grant_permissions() {
    log_info "Granting Key Vault permissions..."
    
    # Try parallel script first, fall back to sequential
    if [ -f "$SCRIPT_DIR/grant-keyvault-permissions-parallel.sh" ]; then
        bash "$SCRIPT_DIR/grant-keyvault-permissions-parallel.sh"
    else
        bash "$SCRIPT_DIR/grant-keyvault-permissions.sh"
    fi
}

store_keys() {
    log_info "Storing validator keys in Key Vaults..."
    
    if [ "$DRY_RUN" = "1" ]; then
        export DRY_RUN=1
    fi
    
    bash "$SCRIPT_DIR/store-nodes-in-keyvault.sh"
}

verify_keyvaults() {
    log_info "Verifying Key Vault configuration..."
    
    # Check Azure login
    
    log_success "Azure authenticated"
    
    # Get all Key Vaults
    VAULTS=$(az keyvault list --query "[].name" -o tsv 2>/dev/null)
    
    if [ -z "$VAULTS" ]; then
        log_error "No Key Vaults found"
        exit 1
    fi
    
    TOTAL=0
    VERIFIED=0
    
    for KV in $VAULTS; do
        TOTAL=$((TOTAL + 1))
        
        # Check Key Vault properties
        KV_RG=$(az keyvault show --name "$KV" --query "resourceGroup" -o tsv 2>/dev/null)
        KV_LOCATION=$(az keyvault show --name "$KV" --query "location" -o tsv 2>/dev/null)
        IS_RBAC=$(az keyvault show --name "$KV" --query "properties.enableRbacAuthorization" -o tsv 2>/dev/null)
        SOFT_DELETE=$(az keyvault show --name "$KV" --query "properties.enableSoftDelete" -o tsv 2>/dev/null)
        PURGE_PROTECTION=$(az keyvault show --name "$KV" --query "properties.enablePurgeProtection" -o tsv 2>/dev/null)
        
        # Check secrets count
        SECRETS_COUNT=$(az keyvault secret list --vault-name "$KV" --query "length(@)" -o tsv 2>/dev/null || echo "0")
        
        echo "Key Vault: $KV"
        echo "  Resource Group: $KV_RG"
        echo "  Location: $KV_LOCATION"
        echo "  RBAC Enabled: $IS_RBAC"
        echo "  Soft Delete: $SOFT_DELETE"
        echo "  Purge Protection: $PURGE_PROTECTION"
        echo "  Secrets: $SECRETS_COUNT"
        
        if [ "$SOFT_DELETE" = "true" ] && [ "$IS_RBAC" = "true" ]; then
            log_success "  Configuration OK"
            VERIFIED=$((VERIFIED + 1))
        else
            log_warn "  Consider enabling RBAC and Soft Delete"
        fi
        
    done
    
    echo "=" | awk '{printf "%-64s\n", ""}'
    echo "📊 SUMMARY"
    echo "=" | awk '{printf "%-64s\n", ""}'
    echo "Total Key Vaults: $TOTAL"
    echo "Verified: $VERIFIED"
    log_success "Verification complete"
}

list_keyvaults() {
    log_info "Listing Key Vaults and secrets..."
    
    VAULTS=$(az keyvault list --query "[].name" -o tsv 2>/dev/null)
    
    if [ -z "$VAULTS" ]; then
        log_error "❌ No Key Vaults found"
        exit 1
    fi
    
    echo "Key Vault Name | Secrets | Resource Group | Location"
    echo "--------------------------------------------------------"
    
    for KV in $VAULTS; do
        SECRETS_COUNT=$(az keyvault secret list --vault-name "$KV" --query "length(@)" -o tsv 2>/dev/null || echo "0")
        KV_RG=$(az keyvault show --name "$KV" --query "resourceGroup" -o tsv 2>/dev/null)
        KV_LOCATION=$(az keyvault show --name "$KV" --query "location" -o tsv 2>/dev/null)
        
        printf "%-40s | %7s | %-20s | %s\n" "$KV" "$SECRETS_COUNT" "$KV_RG" "$KV_LOCATION"
    done
    
}

run_complete() {
    log_info "Running complete Key Vault setup..."
    
    # Step 1: Deploy
    log_warn "Step 1/4: Deploying Key Vaults..."
    deploy_keyvaults
    
    # Step 2: Check status
    log_warn "Step 2/4: Checking deployment status..."
    check_status || {
        log_error "❌ Key Vault deployment incomplete"
        exit 1
    }
    
    # Step 3: Grant permissions
    log_warn "Step 3/4: Granting permissions..."
    grant_permissions
    
    # Step 4: Store keys
    log_warn "Step 4/4: Storing validator keys..."
    store_keys
    
    log_success "✅ Key Vault setup complete!"
}

# Main script
COMMAND="${1:-help}"

case "$COMMAND" in
    deploy)
        deploy_keyvaults
        ;;
    status)
        check_status
        ;;
    permissions)
        grant_permissions
        ;;
    store-keys)
        # Check for --dry-run flag
        if [ "$2" = "--dry-run" ]; then
            export DRY_RUN=1
        fi
        store_keys
        ;;
    verify)
        verify_keyvaults
        ;;
    list)
        list_keyvaults
        ;;
    complete)
        run_complete
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        log_error "Error: Unknown command: $COMMAND"
        show_help
        exit 1
        ;;
esac

