# Shared Functions
# Compatible with both bash and zsh

# Create directory and cd into it
mkcd() {
    mkdir -p "$1" && cd "$1"
}

# Extract archives
extract() {
    if [ -f "$1" ]; then
        case "$1" in
            *.tar.bz2)   tar xjf "$1"     ;;
            *.tar.gz)    tar xzf "$1"     ;;
            *.bz2)       bunzip2 "$1"     ;;
            *.rar)       unrar x "$1"     ;;
            *.gz)        gunzip "$1"      ;;
            *.tar)       tar xf "$1"      ;;
            *.tbz2)      tar xjf "$1"     ;;
            *.tgz)       tar xzf "$1"     ;;
            *.zip)       unzip "$1"       ;;
            *.Z)         uncompress "$1"  ;;
            *.7z)        7z x "$1"        ;;
            *)           echo "'$1' cannot be extracted via extract()" ;;
        esac
    else
        echo "'$1' is not a valid file"
    fi
}

# Find files by name
findfile() {
    find . -type f -name "*$1*" 2>/dev/null
}

# Find directories by name
finddir() {
    find . -type d -name "*$1*" 2>/dev/null
}

# Process grep
psgrep() {
    ps aux | grep "$1" | grep -v grep
}

# Quick backup
backup() {
    cp "$1"{,.bak}
}

# Show disk usage of current directory
usage() {
    du -sh ./* | sort -hr
}

# Package management functions
dotfiles_packages_status() {
    echo "📦 Package Status Check"
    echo "======================"
    
    # Check if package manager is available
    if [[ -f "$HOME/.dotfiles/lib/package_manager.sh" ]]; then
        source "$HOME/.dotfiles/lib/package_manager.sh"
        
        echo "📋 System packages:"
        for pkg in sshuttle curl git vim; do
            case "$pkg" in
                "sshuttle") check="which sshuttle" ;;
                "curl") check="which curl" ;;
                "git") check="which git" ;;
                "vim") check="which vim" ;;
            esac
            if is_package_installed "$check"; then
                echo "  ✅ $pkg"
            else
                echo "  ❌ $pkg (missing)"
            fi
        done
        
        echo ""
        echo "⚡ Binary packages:"
        for pkg in claude-code gemini-cli; do
            case "$pkg" in
                "claude-code") check="which claude" ;;
                "gemini-cli") check="which gemini" ;;
            esac
            if is_package_installed "$check"; then
                echo "  ✅ $pkg"
            else
                echo "  ❌ $pkg (missing)"
            fi
        done
        
        echo ""
        echo "🐙 GitHub packages:"
        for pkg in fzf bat ripgrep fd delta; do
            case "$pkg" in
                "fzf") check="which fzf" ;;
                "bat") check="which bat" ;;
                "ripgrep") check="which rg" ;;
                "fd") check="which fd" ;;
                "delta") check="which delta" ;;
            esac
            if is_package_installed "$check"; then
                echo "  ✅ $pkg"
            else
                echo "  ❌ $pkg (missing)"
            fi
        done
        
    else
        echo "❌ Package manager not available"
    fi
}

dotfiles_install_packages() {
    if [[ -f "$HOME/.dotfiles/lib/package_manager.sh" ]]; then
        source "$HOME/.dotfiles/lib/package_manager.sh"
        install_all_packages
    else
        echo "❌ Package manager not available"
    fi
}

dotfiles_check_packages() {
    if [[ -f "$HOME/.dotfiles/lib/package_manager.sh" ]]; then
        source "$HOME/.dotfiles/lib/package_manager.sh"
        install_all_packages true  # Skip optional packages
    else
        echo "❌ Package manager not available"
    fi
}

# Profile management functions
dotfiles_profile_status() {
    if [[ -f "$HOME/.dotfiles/lib/profile_manager.sh" ]]; then
        source "$HOME/.dotfiles/lib/profile_manager.sh"
        show_profile_status
    else
        echo "❌ Profile manager not available"
    fi
}

dotfiles_profile_set() {
    local new_profile="$1"
    if [[ -z "$new_profile" ]]; then
        echo "Usage: dotfiles_profile_set <profile>"
        echo "Available profiles: server, dev, dev-lite, personal, minimal"
        return 1
    fi
    
    if [[ -f "$HOME/.dotfiles/lib/profile_manager.sh" ]]; then
        source "$HOME/.dotfiles/lib/profile_manager.sh"
        set_profile "$new_profile"
        echo "✅ Profile set to: $new_profile"
        echo "🔄 Run 'dotinstall' to apply profile changes"
    else
        echo "❌ Profile manager not available"
    fi
}

dotfiles_profile_detect() {
    if [[ -f "$HOME/.dotfiles/lib/profile_manager.sh" ]]; then
        source "$HOME/.dotfiles/lib/profile_manager.sh"
        local detected=$(detect_machine_profile)
        echo "🤖 Auto-detected profile: $detected"
        echo "Current profile: $(get_current_profile)"
        echo ""
        echo "Set detected profile? [y/N]: "
        read -r response
        if [[ "$response" =~ ^[Yy]$ ]]; then
            set_profile "$detected"
            echo "✅ Profile updated to: $detected"
        fi
    else
        echo "❌ Profile manager not available"
    fi
}

# Update management functions
dotfiles_update_check() {
    local force=${1:-false}
    if [[ "$1" == "--force" ]]; then
        force=true
    fi
    
    if [[ -f "$HOME/.dotfiles/lib/update_checker.sh" ]]; then
        source "$HOME/.dotfiles/lib/update_checker.sh"
        check_for_updates "$force" true
    else
        echo "❌ Update checker not available"
    fi
}

dotfiles_update_status() {
    if [[ -f "$HOME/.dotfiles/lib/update_checker.sh" ]]; then
        source "$HOME/.dotfiles/lib/update_checker.sh"
        show_update_status
    else
        echo "❌ Update checker not available"
    fi
}

dotfiles_update_install() {
    if [[ -f "$HOME/.dotfiles/lib/update_checker.sh" ]]; then
        source "$HOME/.dotfiles/lib/update_checker.sh"
        update_packages
    else
        echo "❌ Update checker not available"
    fi
}

# Git remote URL conversion functions
git_remote_convert() {
    local remote_name="${1:-origin}"
    local target_format="$2"
    
    # Get current remote URL
    local current_url=$(git remote get-url "$remote_name" 2>/dev/null)
    
    if [[ -z "$current_url" ]]; then
        echo "❌ No remote '$remote_name' found in this repository"
        return 1
    fi
    
    local new_url=""
    local current_format=""
    
    # Detect current format and convert
    if [[ "$current_url" =~ ^git@([^:]+):(.+)\.git$ ]]; then
        # SSH format: git@hostname:user/repo.git
        current_format="ssh"
        local hostname="${BASH_REMATCH[1]}"
        local repo_path="${BASH_REMATCH[2]}"
        new_url="https://${hostname}/${repo_path}.git"
    elif [[ "$current_url" =~ ^https://([^/]+)/(.+)\.git$ ]]; then
        # HTTPS format: https://hostname/user/repo.git
        current_format="https"
        local hostname="${BASH_REMATCH[1]}"
        local repo_path="${BASH_REMATCH[2]}"
        new_url="git@${hostname}:${repo_path}.git"
    elif [[ "$current_url" =~ ^https://([^/]+)/(.+)$ ]]; then
        # HTTPS format without .git suffix
        current_format="https"
        local hostname="${BASH_REMATCH[1]}"
        local repo_path="${BASH_REMATCH[2]}"
        new_url="git@${hostname}:${repo_path}.git"
    else
        echo "❌ Unknown URL format: $current_url"
        return 1
    fi
    
    # Check if target format is specified and matches current
    if [[ -n "$target_format" ]]; then
        if [[ "$target_format" == "$current_format" ]]; then
            echo "✅ Remote '$remote_name' is already in $current_format format"
            echo "   Current URL: $current_url"
            return 0
        elif [[ "$target_format" != "ssh" && "$target_format" != "https" ]]; then
            echo "❌ Invalid target format. Use 'ssh' or 'https'"
            return 1
        fi
        
        # Convert to specific format
        if [[ "$target_format" == "ssh" && "$current_format" == "https" ]]; then
            # Already converted above
            :
        elif [[ "$target_format" == "https" && "$current_format" == "ssh" ]]; then
            # Already converted above
            :
        fi
    fi
    
    # Show current and new URLs
    echo "🔄 Converting git remote '$remote_name'"
    echo "   From ($current_format): $current_url"
    echo "   To   ($([[ $current_format == "ssh" ]] && echo "https" || echo "ssh")): $new_url"
    echo ""
    
    # Confirm change
    echo "Proceed with conversion? [y/N]: "
    read -r response
    if [[ "$response" =~ ^[Yy]$ ]]; then
        if git remote set-url "$remote_name" "$new_url"; then
            echo "✅ Successfully converted remote '$remote_name'"
            echo "   New URL: $(git remote get-url "$remote_name")"
        else
            echo "❌ Failed to update remote URL"
            return 1
        fi
    else
        echo "❌ Conversion cancelled"
        return 1
    fi
}

git_remote_to_ssh() {
    local remote_name="${1:-origin}"
    git_remote_convert "$remote_name" "ssh"
}

git_remote_to_https() {
    local remote_name="${1:-origin}"
    git_remote_convert "$remote_name" "https"
}

git_remote_toggle() {
    local remote_name="${1:-origin}"
    git_remote_convert "$remote_name"
}