#!/usr/bin/env bash
#
# Enhanced SSH Authentication Test Script with SSH Config Alias Support
# Tests the fixed SSH connectivity function with comprehensive diagnostics
#

set -e

# Get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"

# Source the deploy-complete.sh functions
source "$SCRIPT_DIR/deploy-complete.sh"

# Test configuration
TEST_HOST="${1:-thrillwiki-vm}"
TEST_USER="${2:-thrillwiki}"
TEST_PORT="${3:-22}"
TEST_SSH_KEY="${4:-/Users/talor/.ssh/thrillwiki_vm}"

echo "🧪 Enhanced SSH Authentication Detection Test"
echo "[AWS-SECRET-REMOVED]======"
echo ""
echo "🔍 DIAGNOSIS MODE: This test will provide detailed diagnostics for SSH config alias issues"
echo ""
echo "Test Parameters:"
echo "• Host: $TEST_HOST"
echo "• User: $TEST_USER"
echo "• Port: $TEST_PORT"
echo "• SSH Key: $TEST_SSH_KEY"
echo ""

# Enable debug mode for detailed output
export COMPLETE_DEBUG=true

echo "🔍 Pre-test SSH Config Diagnostics"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Test SSH config resolution manually
echo "🔍 Testing SSH config resolution for '$TEST_HOST':"
if command -v ssh >/dev/null 2>&1; then
    echo "• SSH command available: ✅"
    
    echo "• SSH config lookup for '$TEST_HOST':"
    if ssh_config_output=$(ssh -G "$TEST_HOST" 2>&1); then
        echo "  └─ SSH config lookup successful ✅"
        echo "  └─ Key SSH config values:"
        echo "$ssh_config_output" | grep -E "^(hostname|port|user|identityfile)" | while IFS= read -r line; do
            echo "     $line"
        done
        
        # Extract hostname specifically
        resolved_hostname=$(echo "$ssh_config_output" | grep "^hostname " | awk '{print $2}' || echo "$TEST_HOST")
        if [ "$resolved_hostname" != "$TEST_HOST" ]; then
            echo "  └─ SSH alias detected: '$TEST_HOST' → '$resolved_hostname' ✅"
        else
            echo "  └─ No SSH alias (hostname same as input)"
        fi
    else
        echo "  └─ SSH config lookup failed ❌"
        echo "  └─ Error: $ssh_config_output"
    fi
else
    echo "• SSH command not available ❌"
fi

echo ""

# Test manual SSH key file
if [ -n "$TEST_SSH_KEY" ]; then
    echo "🔍 SSH Key Diagnostics:"
    if [ -f "$TEST_SSH_KEY" ]; then
        echo "• SSH key file exists: ✅"
        key_perms=$(ls -la "$TEST_SSH_KEY" | awk '{print $1}')
        echo "• SSH key permissions: $key_perms"
        if [[ "$key_perms" == *"rw-------"* ]] || [[ "$key_perms" == *"r--------"* ]]; then
            echo "  └─ Permissions are secure ✅"
        else
            echo "  └─ Permissions may be too open ⚠️"
        fi
    else
        echo "• SSH key file exists: ❌"
        echo "  └─ File not found: $TEST_SSH_KEY"
    fi
else
    echo "🔍 No SSH key specified - will use SSH agent or SSH config"
fi

echo ""
echo "🔍 Running Enhanced SSH Connectivity Test"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Call the fixed test_ssh_connectivity function
if test_ssh_connectivity "$TEST_HOST" "$TEST_USER" "$TEST_PORT" "$TEST_SSH_KEY" 10; then
    echo ""
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "✅ SSH AUTHENTICATION TEST PASSED!"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    echo "🎉 SUCCESS: The SSH config alias resolution fix is working!"
    echo ""
    echo "What was fixed:"
    echo "• SSH config aliases are now properly resolved for network tests"
    echo "• Ping and port connectivity tests use resolved IP addresses"
    echo "• SSH authentication uses original aliases for proper config application"
    echo "• Enhanced diagnostics provide detailed troubleshooting information"
    echo ""
    echo "The deployment script should now correctly handle your SSH configuration."
    exit 0
else
    echo ""
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "❌ SSH AUTHENTICATION TEST FAILED"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    echo "🔍 The enhanced diagnostics above should help identify the issue."
    echo ""
    echo "💡 Next troubleshooting steps:"
    echo "1. Check the SSH config alias resolution output above"
    echo "2. Verify the resolved IP address is correct"
    echo "3. Test manual SSH connection: ssh $TEST_HOST"
    echo "4. Check network connectivity to resolved IP"
    echo "5. Verify SSH key authentication: ssh -i $TEST_SSH_KEY $TEST_USER@$TEST_HOST"
    echo ""
    echo "📝 Common SSH config alias issues:"
    echo "• Hostname not properly defined in SSH config"
    echo "• SSH key path incorrect in SSH config"
    echo "• Network connectivity to resolved IP"
    echo "• SSH service not running on target host"
    echo ""
    exit 1
fi