# Developer Quality-of-Life Enhancements
# Sourced from main .zshrc

# ============================================================================
# Modern CLI Tool Replacements & Configuration
# ============================================================================

# Use ripgrep for faster grep
alias grep='rg'
rg() {
  command rg --smart-case --pretty "$@"
}

# Better cat with syntax highlighting
alias cat='bat --style=auto'
alias catt='/bin/cat'  # Original cat if needed

# eza as ls alternative (more features than lsd)
if command -v eza &> /dev/null; then
    alias ls='eza --icons --group-directories-first'
    alias ll='eza -lah --icons --group-directories-first --git'
    alias la='eza -a --icons --group-directories-first'
    alias lt='eza --tree --level=2 --icons'
    alias ltree='eza --tree --icons'
fi

# ============================================================================
# Git Enhancements (GitLab-focused)
# ============================================================================

# Quick status aliases
alias gs='git status -sb'
alias gst='git status'
alias gd='git diff'
alias gdc='git diff --cached'
alias gds='git diff --stat'

# Branch management
alias gb='git branch -vv'
alias gba='git branch -a -vv'
alias gbd='git branch -d'
alias gbD='git branch -D'
alias gcb='git checkout -b'
alias gco='git checkout'
alias gcp='git cherry-pick'

# Log aliases with beautiful formatting
alias glog='git log --oneline --decorate --graph --all'
alias gloga='git log --oneline --decorate --graph --all --author'
alias glogg='git log --graph --pretty=format:"%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset" --abbrev-commit'
alias glast='git log -1 HEAD --stat'
alias gwhat='git show'

# Commit shortcuts
alias gc='git commit -v'
alias gca='git commit -v -a'
alias gcm='git commit -m'
alias gcam='git commit -a -m'
alias gcan='git commit --amend --no-edit'
alias gcaa='git commit -a --amend --no-edit'

# Push/Pull
alias gp='git push'
alias gpl='git pull'
alias gpf='git push --force-with-lease'  # Safer force push
alias gpr='git pull --rebase'

# Stash operations
alias gsta='git stash push'
alias gstaa='git stash apply'
alias gstap='git stash pop'
alias gstl='git stash list'
alias gsts='git stash show --text'

# GitLab CLI shortcuts
alias gl='glab'
alias glmr='glab mr'
alias glmrc='glab mr create'
alias glmrv='glab mr view'
alias glmrl='glab mr list'
alias gli='glab issue'
alias glic='glab issue create'
alias gliv='glab issue view'
alias glil='glab issue list'
alias glp='glab pipeline'
alias glr='glab repo'

# ============================================================================
# Smart Git Functions
# ============================================================================

# Unalias any conflicting aliases before defining functions
unalias gsw 2>/dev/null
unalias gfind 2>/dev/null
unalias gdiff 2>/dev/null
unalias gclean 2>/dev/null

# Quick commit with branch name prefix
qc() {
    local branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
    if [[ -z "$branch" ]]; then
        echo "Not in a git repository"
        return 1
    fi

    if [[ "$branch" == "main" ]] || [[ "$branch" == "master" ]]; then
        git commit -m "$*"
    else
        git commit -m "[$branch] $*"
    fi
}

# Quick add and commit
qac() {
    git add -A && qc "$*"
}

# Show files changed in last commit
changed() {
    git show --stat --oneline HEAD
}

# Interactive branch switcher with fzf
gsw() {
    local branch
    branch=$(git branch -a | fzf | sed 's/^[ *]*//' | sed 's/remotes\/origin\///')
    if [[ -n "$branch" ]]; then
        git checkout "$branch"
    fi
}

# Find commits by message
gfind() {
    if [[ -z "$1" ]]; then
        echo "Usage: gfind <search-term>"
        return 1
    fi
    git log --all --grep="$1" --oneline --decorate
}

# Show git diff with delta if available
gdiff() {
    if command -v delta &> /dev/null; then
        git diff "$@" | delta
    else
        git diff "$@"
    fi
}

# Clean up merged branches
gclean() {
    echo "Fetching and pruning..."
    git fetch -p
    printf '\nBranches merged into current branch:\n'
    git branch --merged | command grep -v '^ *\*' | command grep -v -E '^  (main|master|develop)$'
    printf '\nDelete these branches? (y/n)\n'
    read -r response
    if [[ "$response" =~ ^[Yy]$ ]]; then
        git branch --merged | command grep -v '^ *\*' | command grep -v -E '^  (main|master|develop)$' | xargs -n 1 git branch -d
        echo "Cleaned up merged branches!"
    fi
}

# ============================================================================
# Work Directory Navigation & Project Management
# ============================================================================

# Quick jump to work directory
alias work='cd ~/work'
alias w='cd ~/work'

# Project quick-jump function
p() {
    if [[ -z "$1" ]]; then
        cd ~/work && ls -la
        return
    fi

    local project_dir=$(find ~/work -maxdepth 1 -type d -iname "*$1*" -print -quit 2>/dev/null)

    if [[ -n "$project_dir" ]]; then
        if cd "$project_dir"; then
            echo "📂 Switched to: $(basename "$project_dir")"
            # Show quick project info
            [[ -f "package.json" ]] && echo "📦 Node.js project"
            [[ -f "requirements.txt" ]] && echo "🐍 Python project"
            [[ -f "Cargo.toml" ]] && echo "🦀 Rust project"
            [[ -f "go.mod" ]] && echo "🐹 Go project"
            [[ -d ".git" ]] && echo "🔀 Git: $(git rev-parse --abbrev-ref HEAD 2>/dev/null)"
        else
            echo "❌ Failed to change to: $project_dir"
        fi
    else
        echo "❌ Project not found: $1"
        echo "Available projects:"
        ls -1 ~/work
    fi
}

# Enhanced project jump with fzf selection
pf() {
    local project
    project=$(find ~/work -mindepth 1 -maxdepth 1 -type d | xargs -n 1 basename | fzf --height 40% --reverse --prompt="Select project: ")

    if [[ -n "$project" ]]; then
        p "$project"
    fi
}

# Show status of all work projects
pstatus() {
    printf '📊 Project Status Overview\n\n'
    for dir in ~/work/*/; do
        dir="${dir%/}"
        if [[ -d "$dir/.git" ]]; then
            if cd "$dir"; then
                local project=$(basename "$dir")
                local branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
                local changes=$(git status --porcelain 2>/dev/null | wc -l | tr -d ' ')
                local stashes=$(git stash list 2>/dev/null | wc -l | tr -d ' ')

                echo "📁 $project"
                echo "   Branch: $branch"

                if [[ "$changes" -gt 0 ]]; then
                    echo "   ⚠️  Changes: $changes files modified"
                else
                    echo "   ✅ Clean working directory"
                fi

                [[ "$stashes" -gt 0 ]] && echo "   💾 Stashes: $stashes"
                echo ""
            fi
        fi
    done
    cd ~/work
}

# Pull latest for all projects
pup() {
    printf '🔄 Updating all projects in ~/work\n\n'
    for dir in ~/work/*/; do
        dir="${dir%/}"
        if [[ -d "$dir/.git" ]]; then
            if cd "$dir"; then
                local project=$(basename "$dir")
                echo "📁 $project"
                git pull --rebase || echo "   ⚠️  Failed to update"
                echo ""
            fi
        fi
    done
    cd ~/work
}

# Show uncommitted changes across all projects
puncommitted() {
    printf '🔍 Checking for uncommitted changes...\n\n'
    local found=false
    for dir in ~/work/*/; do
        dir="${dir%/}"
        if [[ -d "$dir/.git" ]]; then
            if cd "$dir"; then
                if [[ -n $(git status --porcelain 2>/dev/null) ]]; then
                    found=true
                    local project=$(basename "$dir")
                    echo "📁 $project"
                    git status -sb
                    echo ""
                fi
            fi
        fi
    done

    if [[ "$found" == "false" ]]; then
        echo "✅ All projects have clean working directories"
    fi
    cd ~/work
}

# Create new project with git initialization
pnew() {
    if [[ -z "$1" ]]; then
        echo "Usage: pnew <project-name>"
        return 1
    fi

    local project_path="$HOME/work/$1"
    if [[ -d "$project_path" ]]; then
        echo "❌ Project already exists: $1"
        return 1
    fi

    mkdir -p "$project_path"
    cd "$project_path"
    git init
    echo "# $1" > README.md
    echo "✅ Created new project: $1"
    echo "📂 Location: $project_path"
}

# ============================================================================
# Development Utilities
# ============================================================================

# Quick HTTP server for current directory
serve() {
    local port="${1:-8000}"
    echo "🌐 Starting server on http://localhost:$port"
    python3 -m http.server "$port"
}

# Find file by name in work directory
fw() {
    if [[ -z "$1" ]]; then
        echo "Usage: fw <filename-pattern>"
        return 1
    fi
    fd "$1" ~/work
}

# Find in files (content search) in work directory
fiw() {
    if [[ -z "$1" ]]; then
        echo "Usage: fiw <search-pattern>"
        return 1
    fi
    rg "$1" ~/work
}

# Quick look at package.json scripts
scripts() {
    if [[ -f "package.json" ]]; then
        jq -r '.scripts | to_entries[] | "\(.key): \(.value)"' package.json
    else
        echo "No package.json found in current directory"
    fi
}

# Show recently modified files
recent() {
    local count="${1:-10}"
    fd --type f --changed-within 24h . | head -n "$count"
}

# Disk usage of current directory
duu() {
    du -sh * | sort -hr | head -20
}

# Find large files
large() {
    local size="${1:-100M}"
    echo "Finding files larger than $size..."
    fd --type f --size "+$size" --exec ls -lh {} \; | awk '{print $5, $9}'
}

# Kill process by port
killport() {
    if [[ -z "$1" ]]; then
        echo "Usage: killport <port>"
        return 1
    fi
    local pids
    pids=$(lsof -ti:"$1" 2>/dev/null)
    if [[ -n "$pids" ]]; then
        echo "$pids" | xargs kill -9 2>/dev/null && echo "✅ Killed process on port $1"
    else
        echo "❌ No process found on port $1"
    fi
}

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

# Extract various archive formats
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
}

# Backup a file
backup() {
    if [[ -f "$1" ]]; then
        cp "$1" "$1.backup.$(date +%Y%m%d_%H%M%S)"
        echo "✅ Backup created: $1.backup.$(date +%Y%m%d_%H%M%S)"
    else
        echo "❌ File not found: $1"
    fi
}

# ============================================================================
# Node.js / NPM Shortcuts
# ============================================================================

alias ni='npm install'
alias nid='npm install --save-dev'
alias nr='npm run'
alias nrd='npm run dev'
alias nrb='npm run build'
alias nrt='npm run test'
alias nrs='npm run start'
alias nrl='npm run lint'
alias nrc='npm run clean'
alias nu='npm update'
alias nci='rm -rf node_modules package-lock.json && npm install'

# List available npm scripts
alias npmscripts='command cat package.json | jq .scripts'

# ============================================================================
# Kubernetes / Docker (if needed)
# ============================================================================

alias d='docker'
alias dc='docker-compose'
alias dps='docker ps'
alias dpsa='docker ps -a'
alias di='docker images'
alias dex='docker exec -it'
alias dlog='docker logs -f'
alias dclean='docker system prune -af'

# ============================================================================
# Enhanced FZF Integration
# ============================================================================

# Improved FZF default options for developers
export FZF_DEFAULT_OPTS="
  --height 50%
  --layout=reverse
  --border
  --preview-window=right:60%
  --bind ctrl-/:toggle-preview
  --bind ctrl-u:preview-page-up
  --bind ctrl-d:preview-page-down
"

# Better file preview with bat
export FZF_CTRL_T_OPTS="
  --preview 'bat --color=always --style=numbers --line-range=:500 {}'
  --preview-window 'right:60%:wrap'
"

# Better directory preview
export FZF_ALT_C_OPTS="
  --preview 'eza --tree --level=2 --icons {} || tree -C {} | head -200'
"

# CD to any directory in ~/work with fzf
cdw() {
    local dir
    dir=$(fd --type d --max-depth 5 . ~/work | fzf +m --preview 'eza --tree --level=1 --icons {}')
    if [[ -n "$dir" ]]; then
        cd "$dir"
    fi
}

# ============================================================================
# Completion Enhancements
# ============================================================================

# GitLab CLI completions
if command -v glab &> /dev/null; then
    eval "$(glab completion -s zsh)"
fi

# Directory navigation autocomplete for 'p' function
_p_completion() {
    local projects
    projects=($(command ls -1 ~/work 2>/dev/null))
    _describe 'projects' projects
}
compdef _p_completion p

# ============================================================================
# Performance Monitoring
# ============================================================================

# Show shell startup time
timezsh() {
    shell=${1-$SHELL}
    for i in $(seq 1 10); do /usr/bin/time $shell -i -c exit; done
}

# Show top 10 most used commands
alias topcmd="history | awk '{print \$2}' | sort | uniq -c | sort -rn | head -10"

# ============================================================================
# Helpful Aliases
# ============================================================================

alias code='cursor .'
alias reload='source ~/.zshrc && echo "✅ Shell configuration reloaded"'
alias editrc='cursor ~/dotfiles/zshrc'
alias editdev='cursor ~/dotfiles/zshrc-dev'
alias c='clear'
alias cls='clear'
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
alias ports='lsof -PiTCP -sTCP:LISTEN'
alias myip='curl -s ifconfig.me'
alias speedtest='curl -s https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py | python3 -'

# ============================================================================
# Colorized Man Pages
# ============================================================================

export LESS_TERMCAP_mb=$'\e[1;32m'
export LESS_TERMCAP_md=$'\e[1;32m'
export LESS_TERMCAP_me=$'\e[0m'
export LESS_TERMCAP_se=$'\e[0m'
export LESS_TERMCAP_so=$'\e[01;33m'
export LESS_TERMCAP_ue=$'\e[0m'
export LESS_TERMCAP_us=$'\e[1;4;31m'

echo "💻 Developer enhancements loaded! Type 'devhelp' for quick reference."

# Show available custom commands
devhelp() {
    cat << 'EOF'
🚀 Developer Shell Enhancements - Quick Reference

📂 PROJECT NAVIGATION:
  work, w           → cd to ~/work
  p <name>          → Quick jump to project
  pf                → Fuzzy find and jump to project
  pstatus           → Show status of all projects
  pup               → Pull latest for all projects
  puncommitted      → Show uncommitted changes across projects
  pnew <name>       → Create new project with git init
  cdw               → Fuzzy find any directory in ~/work

🔀 GIT SHORTCUTS:
  gs, gst           → git status
  gd                → git diff
  glog              → Pretty git log graph
  gc <msg>          → Quick commit
  qc <msg>          → Commit with branch prefix
  qac <msg>         → Add all + commit with prefix
  gsw               → Interactive branch switcher
  gclean            → Clean up merged branches
  gfind <term>      → Find commits by message

🔧 GITLAB CLI:
  gl                → glab command
  glmr              → Merge requests
  glmrc             → Create MR
  gli               → Issues
  glp               → Pipelines

📦 NPM SHORTCUTS:
  ni, nid           → npm install
  nr <script>       → npm run
  nrd, nrb, nrt     → dev, build, test
  scripts           → Show package.json scripts

🛠️  UTILITIES:
  fw <name>         → Find file in ~/work
  fiw <term>        → Find in files (grep ~/work)
  killport <port>   → Kill process on port
  serve [port]      → Start HTTP server
  recent [n]        → Show recently modified files
  large [size]      → Find large files
  backup <file>     → Create timestamped backup

⚡️ SYSTEM:
  reload            → Reload shell config
  editrc, editdev   → Edit config files
  devhelp           → Show this help

For more info on any command, type: which <command>
EOF
}
