#!/bin/sh

# CatOps Installation Script
# Recommended usage (secure):
#   curl -fsSL https://get.catops.app/install.sh | AUTH_TOKEN="your_token_here" bash
#
# Local mode (no cloud features):
#   curl -fsSL https://get.catops.app/install.sh | bash
#
# WARNING: Do NOT use 'sudo' with this script - it installs to user's home directory

set -e

# Error handling with trap
cleanup() {
    local exit_code=$?
    if [ $exit_code -ne 0 ]; then
        log_message "ERROR" "Installation failed with exit code: $exit_code"
        print_status "error" "Installation failed. Check /tmp/catops.log for details"
    fi
}
trap cleanup EXIT

# Set locale for Unicode support
export LC_ALL=C.UTF-8
export LANG=C.UTF-8

# Colors - Blue Theme (matching CLI)
BLUE='\033[38;5;75m'
WHITE='\033[1;37m'
GRAY='\033[0;37m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

# Print header
print_header() {
    printf "\n"
    printf "${BLUE} ██████╗ █████╗ ████████╗ ██████╗ ██████╗ ███████╗${NC}\n"
    printf "${BLUE}██╔════╝██╔══██╗╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝${NC}\n"
    printf "${BLUE}██║     ███████║   ██║   ██║   ██║██████╔╝███████╗${NC}\n"
    printf "${BLUE}██║     ██╔══██║   ██║   ██║   ██║██╔═══╝ ╚════██║${NC}\n"
    printf "${BLUE}╚██████╗██║  ██║   ██║   ╚██████╔╝██║     ███████║${NC}\n"
    printf "${BLUE} ╚═════╝╚═╝  ╚═╝   ╚═╝    ╚═════╝ ╚═╝     ╚══════╝${NC}\n"
    printf "\n"
    printf "                    ${WHITE}Server Monitor${NC}\n"
    printf "\n"
}

# Print section
print_section() {
    local title="$1"
    local total_width=70
    local prefix="+- "
    local suffix="-+"
    local title_len=${#title}
    local dash_count=$((total_width - ${#prefix} - ${#suffix} - title_len))
    if [ $dash_count -lt 0 ]; then dash_count=0; fi
    printf "${BLUE}${prefix}${WHITE}%s${BLUE}%s${suffix}${NC}\n" "$title" "$(printf '%*s' $dash_count | sed 's/ /-/g')"
}

# Print section end
print_section_end() {
    local total_width=70
    printf "${BLUE}+%s+${NC}\n" "$(printf '%*s' $((total_width-2)) | sed 's/ /-/g')"
}

# Print status
print_status() {
    local type="$1"
    local message="$2"
    case $type in
        "success") printf "  ${GREEN}✓ $message${NC}\n" ;;
        "info") printf "  ${BLUE}ℹ $message${NC}\n" ;;
        "warning") printf "  ${YELLOW}⚠ $message${NC}\n" ;;
        "error") printf "  ${RED}✗ $message${NC}\n" ;;
    esac
}

# Log message to /tmp/catops.log
log_message() {
    local level="$1"
    local message="$2"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    echo "[$timestamp] $level: $message" >> /tmp/catops.log
}

# Check required dependencies
check_dependencies() {
    local missing_deps=""

    # Check for curl
    if ! command -v curl >/dev/null 2>&1; then
        missing_deps="${missing_deps}curl "
    fi

    # Check for basic Unix utilities
    if ! command -v grep >/dev/null 2>&1; then
        missing_deps="${missing_deps}grep "
    fi

    if [ -n "$missing_deps" ]; then
        print_status "error" "Missing required dependencies: $missing_deps"
        log_message "ERROR" "Missing dependencies: $missing_deps"
        echo ""
        echo "Please install the missing dependencies and try again:"
        echo "  - Debian/Ubuntu: sudo apt-get install curl grep"
        echo "  - RHEL/CentOS: sudo yum install curl grep"
        echo "  - macOS: curl and grep are pre-installed"
        exit 1
    fi

    # Silent success - no need to print
    log_message "INFO" "Dependency check passed"
}

# Detect if running with sudo (which is wrong)
check_sudo() {
    if [ "$(id -u)" = "0" ]; then
        # Running as root
        if [ -n "$SUDO_USER" ]; then
            # Running via sudo
            print_status "error" "Do NOT run this script with sudo!"
            echo ""
            echo "This script installs CatOps to your home directory (\$HOME/.local/bin)."
            echo "Running with sudo will install to /root instead of your user directory."
            echo ""
            echo "Correct usage:"
            echo "  curl -fsSL https://get.catops.app/install.sh | AUTH_TOKEN=\"your_token\" bash"
            echo ""
            log_message "ERROR" "Script run with sudo - aborting (SUDO_USER: $SUDO_USER)"
            exit 1
        else
            # Running as actual root user - just log it, don't show warning
            log_message "WARNING" "Running as actual root user - HOME=$HOME"
        fi
    fi

    # Verify HOME is set correctly
    if [ -z "$HOME" ] || [ "$HOME" = "/" ]; then
        print_status "error" "HOME environment variable not set correctly"
        log_message "ERROR" "Invalid HOME: $HOME"
        exit 1
    fi

    # Silent - just log
    log_message "INFO" "User: $(whoami), HOME: $HOME, UID: $(id -u)"
}

# Security warning about token in command line
print_security_warning() {
    if [ -n "$AUTH_TOKEN" ]; then
        # Silent - just log
        log_message "WARNING" "Token provided via command line (security risk)"
    fi
}

create_directories() {
    mkdir -p "$HOME/.local/bin"
    mkdir -p "$HOME/.catops"
}

download_binary() {
    CLI_DIR="$HOME/.local/bin"

    # Try to use Go binary for current OS/arch
    ARCH=$(uname -m)
    OS=$(uname -s | tr '[:upper:]' '[:lower:]')

    # Map architecture names to binary names
    case $ARCH in
        "x86_64") ARCH="amd64" ;;
        "aarch64") ARCH="arm64" ;;
        "arm64") ARCH="arm64" ;;
    esac

    BINARY_NAME="catops-$OS-$ARCH"

    # GitHub repository
    GITHUB_REPO="mfhonley/catops"
    GITHUB_URL="https://github.com/$GITHUB_REPO/releases/latest/download/$BINARY_NAME"
    CHECKSUM_URL="https://github.com/$GITHUB_REPO/releases/latest/download/$BINARY_NAME.sha256"

    # Log download start
    log_message "INFO" "Download started - Binary: $BINARY_NAME from GitHub Releases"

    # Download binary from GitHub Releases
    print_status "info" "Downloading CatOps from GitHub Releases..."

    if ! curl -fsSL --connect-timeout 10 --max-time 120 "$GITHUB_URL" -o "$CLI_DIR/catops" 2>/dev/null; then
        print_status "error" "Download failed from GitHub Releases"
        log_message "ERROR" "Download failed - Binary: $BINARY_NAME"
        echo ""
        echo "Please check:"
        echo "  1. Your internet connection"
        echo "  2. GitHub is accessible: https://github.com/$GITHUB_REPO/releases"
        echo "  3. Binary exists for your platform: $BINARY_NAME"
        exit 1
    fi

    local source="GitHub Releases"

    # Verify checksum if available (silent)
    local checksum_verified=0
    if command -v sha256sum >/dev/null 2>&1 || command -v shasum >/dev/null 2>&1; then
        local checksum_file="/tmp/catops.sha256"
        curl -fsSL --connect-timeout 5 "$CHECKSUM_URL" -o "$checksum_file" 2>/dev/null || true

        if [ -f "$checksum_file" ]; then
            local expected_checksum=$(cat "$checksum_file" | awk '{print $1}')
            local actual_checksum=""

            if command -v sha256sum >/dev/null 2>&1; then
                actual_checksum=$(sha256sum "$CLI_DIR/catops" | awk '{print $1}')
            elif command -v shasum >/dev/null 2>&1; then
                actual_checksum=$(shasum -a 256 "$CLI_DIR/catops" | awk '{print $1}')
            fi

            if [ "$expected_checksum" = "$actual_checksum" ]; then
                log_message "INFO" "Checksum verified: $actual_checksum"
                checksum_verified=1
            else
                print_status "error" "Checksum verification failed!"
                log_message "ERROR" "Checksum mismatch - expected: $expected_checksum, got: $actual_checksum"
                rm -f "$CLI_DIR/catops"
                exit 1
            fi

            rm -f "$checksum_file"
        else
            log_message "WARNING" "Checksum verification skipped - no checksum file"
        fi
    else
        log_message "WARNING" "Checksum verification skipped - sha256sum not found"
    fi

    chmod +x "$CLI_DIR/catops"

    # Remove macOS quarantine attribute if on macOS
    if [ "$(uname -s)" = "Darwin" ]; then
        xattr -d com.apple.quarantine "$CLI_DIR/catops" 2>/dev/null || true
    fi

    print_status "success" "Downloaded and installed binary"
    log_message "INFO" "Download completed successfully from $source - Binary: $BINARY_NAME"
}

add_to_path() {
    CLI_DIR="$HOME/.local/bin"

    # Determine shell RC file
    if [ -n "$ZSH_VERSION" ]; then
        SHELL_RC="$HOME/.zshrc"
    elif [ -n "$BASH_VERSION" ]; then
        SHELL_RC="$HOME/.bashrc"
    else
        # Try to detect from $SHELL
        case "$SHELL" in
            */zsh) SHELL_RC="$HOME/.zshrc" ;;
            */bash) SHELL_RC="$HOME/.bashrc" ;;
            *) SHELL_RC="$HOME/.profile" ;;
        esac
    fi

    # Add to PATH in RC file if not already there (silent)
    if ! grep -q "$CLI_DIR" "$SHELL_RC" 2>/dev/null; then
        echo 'export PATH="$HOME/.local/bin:$PATH"' >> "$SHELL_RC"
    fi

    # IMPORTANT: Export PATH for current session
    export PATH="$HOME/.local/bin:$PATH"

    # Try to create symlink in /usr/local/bin for system-wide access (silent)
    if [ -w /usr/local/bin ] 2>/dev/null; then
        ln -sf "$CLI_DIR/catops" /usr/local/bin/catops 2>/dev/null
        if [ $? -eq 0 ]; then
            log_message "INFO" "Symlink created: /usr/local/bin/catops -> $CLI_DIR/catops"
        fi
    fi

    # Verify catops is accessible (silent check, only show if not available)
    if command -v catops >/dev/null 2>&1; then
        log_message "INFO" "catops command verified in PATH: $(command -v catops)"
    else
        log_message "WARNING" "catops not immediately available in PATH"
    fi
}

auto_configure() {
	# Create config directory
	mkdir -p "$HOME/.catops"

	# Start building config content
	CONFIG_CONTENT=""

	# Add auth token if provided (for Cloud Mode)
	if [ -n "$AUTH_TOKEN" ]; then
		CONFIG_CONTENT="${CONFIG_CONTENT}auth_token: $AUTH_TOKEN
"
		log_message "INFO" "Authentication token configured - Cloud Mode enabled"
	else
		log_message "INFO" "No auth token provided - Running in Local Mode"
		log_message "INFO" "Use 'catops auth login <token>' to enable Cloud Mode with Telegram alerts"
	fi

	# Add default thresholds
	CONFIG_CONTENT="${CONFIG_CONTENT}cpu_threshold: 80.0
mem_threshold: 80.0
disk_threshold: 90.0
"
	
	# Write config file
	echo "$CONFIG_CONTENT" > "$HOME/.catops/config.yaml"
}

test_installation() {
    CLI_DIR="$HOME/.local/bin"
    CATOPS_BINARY="$CLI_DIR/catops"
    
    # Log test start
    log_message "INFO" "Testing installation - Binary: $CATOPS_BINARY"
    
    # Check if binary exists
    if [ ! -f "$CATOPS_BINARY" ]; then
        log_message "ERROR" "Binary not found: $CATOPS_BINARY"
        print_status "error" "Binary not found: $CATOPS_BINARY"
        exit 1
    fi
    
    # Check binary permissions
    if [ ! -x "$CATOPS_BINARY" ]; then
        log_message "ERROR" "Binary not executable: $CATOPS_BINARY"
        print_status "error" "Binary not executable: $CATOPS_BINARY"
        exit 1
    fi
    
    # Log binary info
    log_message "INFO" "Binary exists and is executable"
    log_message "INFO" "Binary size: $(ls -lh "$CATOPS_BINARY" | awk '{print $5}')"
    log_message "INFO" "Binary permissions: $(ls -la "$CATOPS_BINARY" | awk '{print $1}')"
    
    # Test the binary with more detailed logging
    log_message "INFO" "Testing binary with --help flag..."
    if "$CATOPS_BINARY" --help >/dev/null 2>&1; then
        log_message "SUCCESS" "Binary test passed - --help flag works"
        print_status "success" "Installation test passed"
    else
        local exit_code=$?
        log_message "ERROR" "Binary test failed with exit code: $exit_code"
        log_message "ERROR" "Binary output: $("$CATOPS_BINARY" --help 2>&1)"
        print_status "error" "Installation failed - binary test failed"
        exit 1
    fi
}

auto_start() {
	CLI_DIR="$HOME/.local/bin"
	
	# Create autostart service (without manual start to avoid duplicate Telegram messages)
	if [ "$OS" = "linux" ]; then
		create_systemd_service
	elif [ "$OS" = "darwin" ]; then
		create_launchd_service
	else
		# Fallback for other systems
		create_crontab_service
	fi
	
	print_status "success" "Autostart service configured"
	print_status "info" "Monitoring will start automatically on boot"
}

create_systemd_service() {
	# Check if systemd is available
	if ! command -v systemctl >/dev/null 2>&1; then
		return
	fi
	
	# Create systemd user directory
	mkdir -p "$HOME/.config/systemd/user"
	
	# Create wrapper script for duplicate protection
	local wrapper_script="$HOME/.catops/start_catops.sh"
	cat > "$wrapper_script" << 'EOF'
#!/bin/bash
# Wrapper script to start catops daemon safely
CLI_DIR="$HOME/.local/bin"

# Kill any duplicate processes first
pids=$(pgrep -f "catops daemon" 2>/dev/null)
if [ -n "$pids" ]; then
    pid_count=$(echo "$pids" | wc -l)
    if [ "$pid_count" -gt 1 ]; then
        # Keep the first process, kill the rest
        first_pid=$(echo "$pids" | head -n1)
        echo "$pids" | tail -n +2 | while read pid; do
            if [ "$pid" != "$first_pid" ]; then
                kill "$pid" 2>/dev/null
            fi
        done
    fi
fi

# Start the daemon
exec "$CLI_DIR/catops" daemon
EOF
	chmod +x "$wrapper_script"
	
	# Create service file
	cat > "$HOME/.config/systemd/user/catops.service" << EOF
[Unit]
Description=CatOps System Monitor
After=network.target

[Service]
Type=simple
ExecStart=$wrapper_script
Restart=always
RestartSec=10
Environment=PATH=$CLI_DIR:/usr/local/bin:/usr/bin:/bin

[Install]
WantedBy=default.target
EOF

	# Try to enable the service (without starting)
	if systemctl --user daemon-reload 2>/dev/null; then
		if systemctl --user enable catops.service 2>/dev/null; then
			print_status "success" "Systemd service created and enabled"
			# Start service immediately if enabled successfully
			if systemctl --user start catops.service 2>/dev/null; then
				print_status "success" "Monitoring service started via systemd"
				log_message "SUCCESS" "Monitoring service started via systemd"
			else
				# Kill any duplicate processes before starting manually
				kill_duplicate_processes
				if nohup "$CLI_DIR/catops" daemon > /dev/null 2>&1 & then
					print_status "success" "Monitoring service started manually"
					log_message "SUCCESS" "Monitoring service started manually after systemd failure"
				fi
			fi
		else
			# Start service manually if enable failed
			kill_duplicate_processes
			if nohup "$CLI_DIR/catops" daemon > /dev/null 2>&1 & then
				print_status "success" "Monitoring service started manually"
				log_message "SUCCESS" "Monitoring service started manually after launchd failure"
			fi
		fi
	else
		# Fallback: start service manually if systemd fails
		if nohup "$CLI_DIR/catops" daemon > /dev/null 2>&1 & then
			print_status "success" "Monitoring service started manually"
		fi
	fi
}

create_launchd_service() {
	# Create wrapper script for duplicate protection
	local wrapper_script="$HOME/.catops/start_catops.sh"
	cat > "$wrapper_script" << 'EOF'
#!/bin/bash
# Wrapper script to start catops daemon safely
CLI_DIR="$HOME/.local/bin"

# Kill any duplicate processes first
pids=$(pgrep -f "catops daemon" 2>/dev/null)
if [ -n "$pids" ]; then
    pid_count=$(echo "$pids" | wc -l)
    if [ "$pid_count" -gt 1 ]; then
        # Keep the first process, kill the rest
        first_pid=$(echo "$pids" | head -n1)
        echo "$pids" | tail -n +2 | while read pid; do
            if [ "$pid" != "$first_pid" ]; then
                kill "$pid" 2>/dev/null
            fi
        done
    fi
fi

# Start the daemon
exec "$CLI_DIR/catops" daemon
EOF
	chmod +x "$wrapper_script"
	
	# Create launchd plist file
	cat > "$HOME/Library/LaunchAgents/com.catops.monitor.plist" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>Label</key>
		<string>com.catops.monitor</string>
	<key>ProgramArguments</key>
	<array>
		<string>$wrapper_script</string>
	</array>
	<key>RunAtLoad</key>
	<true/>
	<key>KeepAlive</key>
	<true/>
	<key>StandardOutPath</key>
		<string>/tmp/catops.log</string>
	<key>StandardErrorPath</key>
		<string>/tmp/catops.log</string>
</dict>
</plist>
EOF

	# Load the service
	if launchctl load "$HOME/Library/LaunchAgents/com.catops.monitor.plist" 2>/dev/null; then
		print_status "success" "Launchd service created and enabled"
	else
		print_status "success" "Launchd service created and enabled"
	fi
}

create_crontab_service() {
	print_status "info" "Creating crontab entry for autostart..."
	
	CLI_DIR="$HOME/.local/bin"
	
	# Add to crontab if not already present
	if ! crontab -l 2>/dev/null | grep -q "catops daemon"; then
		# Use a wrapper script that kills duplicates before starting
		local wrapper_script="$HOME/.catops/start_catops.sh"
		cat > "$wrapper_script" << 'EOF'
#!/bin/bash
# Wrapper script to start catops daemon safely
CLI_DIR="$HOME/.local/bin"

# Kill any duplicate processes first
pids=$(pgrep -f "catops daemon" 2>/dev/null)
if [ -n "$pids" ]; then
    pid_count=$(echo "$pids" | wc -l)
    if [ "$pid_count" -gt 1 ]; then
        # Keep the first process, kill the rest
        first_pid=$(echo "$pids" | head -n1)
        echo "$pids" | tail -n +2 | while read pid; do
            if [ "$pid" != "$first_pid" ]; then
                kill "$pid" 2>/dev/null
            fi
        done
    fi
fi

# Start the daemon
exec "$CLI_DIR/catops" daemon
EOF
		chmod +x "$wrapper_script"
		
		(crontab -l 2>/dev/null; echo "@reboot $wrapper_script > /dev/null 2>&1 &") | crontab -
		print_status "success" "Crontab entry created for autostart"
	else
		print_status "success" "Crontab entry created for autostart"
	fi
}

# Function to kill duplicate processes
kill_duplicate_processes() {
    log_message "INFO" "Checking for duplicate catops processes..."
    
    # Find all catops daemon processes
    local pids=$(pgrep -f "catops daemon" 2>/dev/null)
    if [ -n "$pids" ]; then
        local pid_count=$(echo "$pids" | wc -l)
        if [ "$pid_count" -gt 1 ]; then
            log_message "WARNING" "Found $pid_count duplicate catops daemon processes"
            
            # Keep the first process, kill the rest
            local first_pid=$(echo "$pids" | head -n1)
            echo "$pids" | tail -n +2 | while read pid; do
                if [ "$pid" != "$first_pid" ]; then
                    log_message "INFO" "Killing duplicate process PID: $pid"
                    kill "$pid" 2>/dev/null
                fi
            done
            
            log_message "SUCCESS" "Duplicate processes killed, keeping PID: $first_pid"
        else
            log_message "INFO" "Only one catops daemon process running (PID: $(echo $pids))"
        fi
    else
        log_message "INFO" "No catops daemon processes found"
    fi
}

# Function to start monitoring service safely
auto_start() {
    local CLI_DIR="$HOME/.local/bin"

    # Kill any duplicate processes first
    kill_duplicate_processes

    # Check if service is already running
    if pgrep -f "catops daemon" >/dev/null; then
        print_status "info" "Monitoring service already running"
        log_message "INFO" "Monitoring service already running"
        return 0
    fi

    # Try to find catops binary
    local CATOPS_BIN=""
    if command -v catops >/dev/null 2>&1; then
        CATOPS_BIN="catops"
        log_message "INFO" "Using catops from PATH: $(command -v catops)"
    elif [ -f "$CLI_DIR/catops" ]; then
        CATOPS_BIN="$CLI_DIR/catops"
        log_message "INFO" "Using catops from CLI_DIR: $CATOPS_BIN"
    elif [ -f "/usr/local/bin/catops" ]; then
        CATOPS_BIN="/usr/local/bin/catops"
        log_message "INFO" "Using catops from /usr/local/bin: $CATOPS_BIN"
    else
        print_status "error" "catops binary not found"
        log_message "ERROR" "catops binary not found in PATH, $CLI_DIR, or /usr/local/bin"
        return 1
    fi

    # Start the service with full path
    if nohup "$CATOPS_BIN" daemon > /dev/null 2>&1 & then
        local start_pid=$!
        sleep 1  # Give it a moment to start

        # Verify it's actually running
        if kill -0 $start_pid 2>/dev/null; then
            print_status "success" "Monitoring service started successfully (PID: $start_pid)"
            log_message "SUCCESS" "Monitoring service started via auto_start (PID: $start_pid, Binary: $CATOPS_BIN)"
            return 0
        else
            print_status "error" "Monitoring service failed to start"
            log_message "ERROR" "Monitoring service process died immediately after start"
            return 1
        fi
    else
        print_status "error" "Failed to start monitoring service"
        log_message "ERROR" "Failed to execute: nohup $CATOPS_BIN daemon"
        return 1
    fi
}

# Function to get CPU cores
get_cpu_cores() {
    if [ "$(uname -s)" = "Darwin" ]; then
        # macOS
        sysctl -n hw.ncpu 2>/dev/null || echo "0"
    elif [ "$(uname -s)" = "Linux" ]; then
        # Linux
        nproc 2>/dev/null || grep -c ^processor /proc/cpuinfo 2>/dev/null || echo "0"
    else
        echo "0"
    fi
}

# Function to get total memory in GB
get_total_memory() {
    if [ "$(uname -s)" = "Darwin" ]; then
        # macOS
        local memory_bytes=$(sysctl -n hw.memsize 2>/dev/null || echo "0")
        echo $((memory_bytes / 1024 / 1024 / 1024))
    elif [ "$(uname -s)" = "Linux" ]; then
        # Linux
        local memory_kb=$(grep MemTotal /proc/meminfo 2>/dev/null | awk '{print $2}' || echo "0")
        echo $((memory_kb / 1024 / 1024))
    else
        echo "0"
    fi
}

# Function to get total storage in GB
get_total_storage() {
    if [ "$(uname -s)" = "Darwin" ]; then
        # macOS
        df -g / | tail -1 | awk '{print $2}' 2>/dev/null || echo "0"
    elif [ "$(uname -s)" = "Linux" ]; then
        # Linux
        df -BG / | tail -1 | awk '{print $2}' | sed 's/G//' 2>/dev/null || echo "0"
    else
        echo "0"
    fi
}

# Send installation statistics
send_install_stats() {
    local platform=$(uname -s | tr '[:upper:]' '[:lower:]')
    local arch=$(uname -m)
    case $arch in
        "x86_64") arch="amd64" ;;
        "aarch64") arch="arm64" ;;
        "arm64") arch="arm64" ;;
    esac
    
    # Get server specifications
    local cpu_cores=$(get_cpu_cores)
    local total_memory=$(get_total_memory)
    local total_storage=$(get_total_storage)
    
    # Log server specs for debugging
    log_message "DEBUG" "Server specs - CPU: ${cpu_cores} cores, Memory: ${total_memory} GB, Storage: ${total_storage} GB"
    
    # Подготавливаем данные для отправки
    local data="{\"platform\":\"$platform\",\"architecture\":\"$arch\",\"type\":\"install\",\"timestamp\":\"$(date +%s)\""
    
    # Если есть AUTH_TOKEN, добавляем информацию о сервере
    if [ -n "$AUTH_TOKEN" ]; then
        local hostname=$(hostname)
        if [ -n "$hostname" ]; then
            # Экранируем JSON
            local escaped_token=$(echo "$AUTH_TOKEN" | sed 's/"/\\"/g')
            # Get CatOps version from backend API
            local catops_version="0.0.1"  # Default fallback
            
            # Try to get version from backend API
            local version_response=$(curl -s -X GET "https://api.catops.app/api/versions/check" \
                -H "Content-Type: application/json" \
                -H "User-Agent: CatOps-CLI/1.0.0" 2>/dev/null)
            
            if [ $? -eq 0 ] && [ -n "$version_response" ]; then
                # Extract version from JSON response using grep and sed
                local extracted_version=$(echo "$version_response" | grep -o '"version":"[^"]*"' | sed 's/"version":"//;s/"//')
                if [ -n "$extracted_version" ] && [ "$extracted_version" != "null" ]; then
                    catops_version="$extracted_version"
                    log_message "DEBUG" "Using version from backend API: $catops_version"
                else
                    log_message "DEBUG" "No version in API response, using default: $catops_version"
                fi
            else
                log_message "DEBUG" "Failed to get version from API, using default: $catops_version"
            fi
            
            data="${data},\"user_token\":\"$escaped_token\",\"server_info\":{\"hostname\":\"$hostname\",\"os_type\":\"$platform\",\"os_version\":\"$platform\",\"catops_version\":\"$catops_version\"}"
            
            # Add server specifications
            data="${data},\"cpu_cores\":$cpu_cores,\"total_memory\":$total_memory,\"total_storage\":$total_storage"
        fi
    fi
    
    data="${data}}"
    
    # Log the JSON data being sent for debugging
    log_message "DEBUG" "Sending JSON data: $data"
    
    # Log installation request start
    log_message "INFO" "Installation request started - URL: https://api.catops.app/api/cli/install"

    # Send stats and get response
    local response=$(curl -s -X POST "https://api.catops.app/api/cli/install" \
        -H "Content-Type: application/json" \
        -H "User-Agent: CatOps-CLI/1.0.0" \
        -H "X-Platform: $platform" \
        -H "X-Version: 1.0.0" \
        -d "$data" 2>/dev/null || echo '{"success":false}')
    
    # Extract server_token from response if successful (same approach as Go code)
    if [ -n "$response" ]; then
        # Log full response for debugging
        log_message "INFO" "Full response received: $response"
        
        # Check if response contains success field (same as Go: result["success"] == true)
        if echo "$response" | grep -q '"success"'; then
            # Extract user_token and server_id from data (same as Go code)
            local user_token=""
            local server_id=""

            # Method 1: Use jq for proper JSON parsing (same logic as Go)
            if command -v jq >/dev/null 2>&1; then
                user_token=$(echo "$response" | jq -r '.data.user_token // empty' 2>/dev/null)
                server_id=$(echo "$response" | jq -r '.data.server_id // empty' 2>/dev/null)
                if [ -n "$user_token" ]; then
                    log_message "INFO" "user_token extracted with jq: $user_token"
                fi
                if [ -n "$server_id" ]; then
                    log_message "INFO" "server_id extracted with jq: $server_id"
                fi
            fi

            # Method 2: Fallback to grep if jq not available
            if [ -z "$user_token" ]; then
                user_token=$(echo "$response" | grep -o '"user_token":"[^"]*"' | cut -d'"' -f4)
                if [ -n "$user_token" ]; then
                    log_message "INFO" "user_token extracted with grep fallback: $user_token"
                fi
            fi
            if [ -z "$server_id" ]; then
                server_id=$(echo "$response" | grep -o '"server_id":"[^"]*"' | cut -d'"' -f4)
                if [ -n "$server_id" ]; then
                    log_message "INFO" "server_id extracted with grep fallback: $server_id"
                fi
            fi

            # Extract user_token from response (permanent token for CLI)
            local permanent_token=""
            if command -v jq >/dev/null 2>&1; then
                permanent_token=$(echo "$response" | jq -r '.data.user_token // empty' 2>/dev/null)
                if [ -n "$permanent_token" ]; then
                    log_message "INFO" "permanent_token extracted with jq: ${permanent_token:0:20}..."
                fi
            fi

            # Fallback to grep if jq not available
            if [ -z "$permanent_token" ]; then
                permanent_token=$(echo "$response" | grep -o '"user_token":"[^"]*"' | cut -d'"' -f4)
                if [ -n "$permanent_token" ]; then
                    log_message "INFO" "permanent_token extracted with grep fallback: ${permanent_token:0:20}..."
                fi
            fi

            # Save server_id and permanent_token to config
            if [ -n "$server_id" ]; then
                local config_file="$HOME/.catops/config.yaml"
                if [ -f "$config_file" ]; then
                    # Add server_id to config if not already present
                    if ! grep -q "server_id:" "$config_file"; then
                        echo "server_id: $server_id" >> "$config_file"
                        log_message "INFO" "server_id added to config: $server_id"
                    else
                        # Update existing server_id
                        sed -i.bak "s/server_id:.*/server_id: $server_id/" "$config_file"
                        log_message "INFO" "server_id updated in config: $server_id"
                    fi

                    # Replace AUTH_TOKEN with permanent_token if we got one
                    if [ -n "$permanent_token" ]; then
                        if grep -q "auth_token:" "$config_file"; then
                            sed -i.bak "s|auth_token:.*|auth_token: $permanent_token|" "$config_file"
                            log_message "INFO" "auth_token replaced with permanent token in config"
                        else
                            echo "auth_token: $permanent_token" >> "$config_file"
                            log_message "INFO" "permanent token added to config as auth_token"
                        fi
                    else
                        log_message "WARNING" "permanent_token not found in response, keeping original AUTH_TOKEN"
                    fi
                else
                    log_message "ERROR" "Config file not found: $config_file"
                fi
            else
                log_message "WARNING" "server_id not found in response - tried jq and grep methods"
                log_message "WARNING" "Response structure: $(echo "$response" | head -c 200)..."
            fi
        else
            log_message "ERROR" "Installation request failed - no success field in response: $response"
        fi
    else
        log_message "ERROR" "Installation request failed - no response"
    fi
}

main() {
    # Log installation start
    log_message "INFO" "Installation script started"

    print_header

    # Pre-installation checks
    print_section "Pre-installation Checks"
    check_sudo
    check_dependencies
    print_security_warning
    print_section_end

    print_section "Installing CatOps"
    create_directories
    download_binary
    add_to_path
    auto_configure
    test_installation
    
    # Send installation statistics FIRST to get server_token
    send_install_stats
    
    # Start service AFTER getting server_token
    auto_start
    print_section_end
    
    print_section "Installation Complete"
    print_status "success" "CatOps installed and running"

    # Only show PATH warning if needed
    if ! command -v catops >/dev/null 2>&1; then
        echo ""
        echo "${YELLOW}⚠️  Run this to use catops now:${NC} ${GREEN}export PATH=\"\$HOME/.local/bin:\$PATH\"${NC}"
        echo "${GRAY}   Or restart your terminal${NC}"
    fi

    # Final check for duplicate processes after installation
    kill_duplicate_processes

    # Log installation completion
    log_message "INFO" "Installation completed successfully"

    print_section_end
}

main 