#!/usr/bin/env bash

# Function to purge all traces
purge_appimage_integrator() {
    echo "Removing AppImage Integrator..."
    
    # Remove scripts
    sudo rm -f /usr/local/bin/install_appimages
    sudo rm -f /usr/local/bin/ai
    sudo rm -f /usr/local/bin/setup_appimage_integrator
    
    # Remove completion
    sudo rm -f /etc/bash_completion.d/appimage-integrator
    sudo rm -f /usr/share/bash-completion/completions/ai
    
    # Remove config
    rm -rf "$HOME/.config/appimage_desktop_integrator"
    
    # Remove desktop entries
    find "$HOME/.local/share/applications" -name "*.desktop" \
         -exec grep -l "Generated by AppImage Integrator" {} \; -delete
    
    echo "✓ AppImage Integrator removed"
}

# Install function
install_appimage_integrator() {
    echo "Installing AppImage Integrator..."
    echo ""
    
    # Create config directory
    mkdir -p "$HOME/.config/appimage_desktop_integrator"
    
    # Install main script with version injection
    current_version=$(cat "$script_dir/VERSION" 2>/dev/null || echo "2.1.0")
    
    # Create temporary script with embedded version
    temp_script="/tmp/install_appimages_$$.sh"
    sed "s/__VERSION_PLACEHOLDER__/$current_version/g" "$script_dir/install_appimages.sh" > "$temp_script"
    
    # Install the version-injected script
    sudo mv "$temp_script" /usr/local/bin/install_appimages
    sudo chmod +x /usr/local/bin/install_appimages
    
    # Create simple 'ai' alias
    sudo ln -sf /usr/local/bin/install_appimages /usr/local/bin/ai
    
    # Install setup script
    sudo cp "$script_dir/setup_appimage_integrator.sh" /usr/local/bin/setup_appimage_integrator
    sudo chmod +x /usr/local/bin/setup_appimage_integrator
    
    # Version is now embedded in script - no config file needed
    
    # Install bash completion
    if [ -f "$script_dir/ai-completion.bash" ]; then
        if [ -d "/usr/share/bash-completion/completions" ]; then
            sudo cp "$script_dir/ai-completion.bash" /usr/share/bash-completion/completions/ai
            sudo cp "$script_dir/ai-completion.bash" /usr/share/bash-completion/completions/install_appimages
        elif [ -d "/etc/bash_completion.d" ]; then
            sudo cp "$script_dir/ai-completion.bash" /etc/bash_completion.d/appimage-integrator
        fi
    fi
    
    # Create initial config
    if [ ! -f "$HOME/.config/appimage_desktop_integrator/config.ini" ]; then
        # Check for old config in current directory
        if [ -f "$script_dir/config.ini" ]; then
            echo "Found existing config, migrating and expanding paths..."
            
            # Read the config and expand any ~ or $HOME references
            while IFS='=' read -r key value; do
                # Skip comments and empty lines
                [[ "$key" =~ ^[[:space:]]*# ]] && continue
                [[ -z "$key" ]] && continue
                
                # Expand ~ to $HOME in the value
                expanded_value="${value//\~/$HOME}"
                # Also evaluate any $HOME references
                expanded_value=$(eval echo "$expanded_value")
                
                # Write to new config with expanded paths
                echo "${key}=${expanded_value}" >> "$HOME/.config/appimage_desktop_integrator/config.ini.tmp"
            done < "$script_dir/config.ini"
            
            # Move the temporary file to the final location
            mv "$HOME/.config/appimage_desktop_integrator/config.ini.tmp" "$HOME/.config/appimage_desktop_integrator/config.ini"
            
            # Update old config format if needed
            if grep -q "^appimages_dir=" "$HOME/.config/appimage_desktop_integrator/config.ini"; then
                sed -i 's/^appimages_dir=/# Legacy single directory\n# appimages_dir=/' "$HOME/.config/appimage_desktop_integrator/config.ini"
                echo "" >> "$HOME/.config/appimage_desktop_integrator/config.ini"
                echo "# Multiple directories supported (array format)" >> "$HOME/.config/appimage_desktop_integrator/config.ini"
                echo "appimages_dirs=(\"$HOME/Applications\" \"$HOME/AppImages\" \"$HOME/apps\")" >> "$HOME/.config/appimage_desktop_integrator/config.ini"
            fi
        else
            cat > "$HOME/.config/appimage_desktop_integrator/config.ini" <<EOL
# AppImage Integrator Configuration
icons_dir=$HOME/.local/share/icons/appimage-integrator
update_dir=$HOME/.local/share/applications

# You can specify multiple directories for AppImages
appimages_dirs=("$HOME/Applications" "$HOME/AppImages" "$HOME/apps")
EOL
        fi
    fi
    
    # Create default directories
    mkdir -p "$HOME/Applications"
    mkdir -p "$HOME/.local/share/icons/appimage-integrator"
    
    echo "✓ Installation complete!"
    echo ""
    echo "Quick Start Guide:"
    echo "=================="
    echo ""
    echo "  ai              - Show help"
    echo "  ai find         - Find AppImages on your system"
    echo "  ai install      - Install AppImages interactively"
    echo "  ai list         - List integrated AppImages"
    echo "  ai status       - Show configuration"
    echo ""
    echo "The 'ai' command is now available system-wide."
    echo "Restart your terminal for tab completion to work."
    echo ""
}

# Main script
script_dir=$(pwd)

if [ "$1" = "--purge" ]; then
    purge_appimage_integrator
    exit 0
fi

if [ -z "$BASH_VERSION" ]; then
    echo "This script requires Bash. Please run with: bash $0"
    exit 1
fi

if ! command -v wget >/dev/null 2>&1; then
    echo "wget is required. Please install it first."
    exit 1
fi

echo "AppImage Desktop Integrator Setup"
echo "================================="
echo ""

# Download files if not present locally
if [ ! -f "$script_dir/install_appimages.sh" ]; then
    echo "Downloading latest version..."
    wget -q "https://raw.githubusercontent.com/8ByteSword/appimage-desktop-integrator/main/install_appimages.sh" \
         -O "$script_dir/install_appimages.sh" || {
        echo "Failed to download. Please check your internet connection."
        exit 1
    }
fi

if [ ! -f "$script_dir/VERSION" ]; then
    wget -q "https://raw.githubusercontent.com/8ByteSword/appimage-desktop-integrator/main/VERSION" \
         -O "$script_dir/VERSION" 2>/dev/null || echo "1.2.0" > "$script_dir/VERSION"
fi

if [ ! -f "$script_dir/ai-completion.bash" ]; then
    wget -q "https://raw.githubusercontent.com/8ByteSword/appimage-desktop-integrator/main/ai-completion.bash" \
         -O "$script_dir/ai-completion.bash" 2>/dev/null || true
fi

# Make executable
chmod +x "$script_dir/install_appimages.sh"

# Install
install_appimage_integrator