#!/usr/bin/env bash
# ==============================================================================
# Terminal Aesthetics & Oh-My-Zsh Universal Installer
# Replicates prompt aesthetics (), Oh My Zsh, custom plugins,
# Neowofetch banner, Screen session config, and comprehensive aliases/functions.
# Compatible with: Debian/Ubuntu/Kali, Arch Linux, Fedora/RHEL, Alpine, and macOS.
# ==============================================================================

set -e

# ANSI Color codes for installer output
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
YELLOW='\033[1;33m'
BOLD='\033[1m'
NC='\033[0m' # No Color

info() { echo -e "${CYAN}[*]${NC} $1"; }
success() { echo -e "${GREEN}[+]${NC} $1"; }
warn() { echo -e "${YELLOW}[!]${NC} $1"; }
error() { echo -e "${RED}[-]${NC} $1"; }

echo -e "${BLUE}${BOLD}"
cat << "BANNER"
  ___________________________________________________________
 /                                                           \
 |      Terminal Prompt Aesthetics & Oh-My-Zsh Installer     |
 \___________________________________________________________/
BANNER
echo -e "${NC}"

# Detect if running as root or standard user
IS_ROOT=false
if [ "$EUID" -eq 0 ]; then
    IS_ROOT=true
fi

# Detect package manager
PKG_MGR=""
if command -v apt-get >/dev/null 2>&1; then
    PKG_MGR="apt"
elif command -v pacman >/dev/null 2>&1; then
    PKG_MGR="pacman"
elif command -v dnf >/dev/null 2>&1; then
    PKG_MGR="dnf"
elif command -v zypper >/dev/null 2>&1; then
    PKG_MGR="zypper"
elif command -v apk >/dev/null 2>&1; then
    PKG_MGR="apk"
elif command -v brew >/dev/null 2>&1; then
    PKG_MGR="brew"
fi

# ------------------------------------------------------------------------------
# 1. Install System Dependencies
# ------------------------------------------------------------------------------
info "Detected package manager: ${PKG_MGR:-none}"
info "Installing required packages (zsh, git, curl, screen, jq, font utilities)..."

install_packages() {
    case "$PKG_MGR" in
        apt)
            local pkgs=(zsh git curl screen jq fonts-firacode fontconfig)
            local opt_pkgs=(fonts-font-awesome fonts-powerline neowofetch)
            if [ "$IS_ROOT" = true ]; then
                apt-get update -qq || true
                apt-get install -y "${pkgs[@]}" 2>/dev/null || true
                for p in "${opt_pkgs[@]}"; do
                    apt-get install -y "$p" 2>/dev/null || true
                done
            elif command -v sudo >/dev/null 2>&1; then
                sudo apt-get update -qq || true
                sudo apt-get install -y "${pkgs[@]}" 2>/dev/null || true
                for p in "${opt_pkgs[@]}"; do
                    sudo apt-get install -y "$p" 2>/dev/null || true
                done
            else
                warn "Sudo unavailable. Attempting to proceed with user-space fallbacks."
            fi
            ;;
        pacman)
            local pkgs=(zsh git curl screen jq ttf-fira-code fontconfig)
            if [ "$IS_ROOT" = true ]; then
                pacman -Sy --noconfirm "${pkgs[@]}" 2>/dev/null || true
            elif command -v sudo >/dev/null 2>&1; then
                sudo pacman -Sy --noconfirm "${pkgs[@]}" 2>/dev/null || true
            fi
            ;;
        dnf)
            local pkgs=(zsh git curl screen jq fira-code-fonts fontconfig)
            if [ "$IS_ROOT" = true ]; then
                dnf install -y "${pkgs[@]}" 2>/dev/null || true
            elif command -v sudo >/dev/null 2>&1; then
                sudo dnf install -y "${pkgs[@]}" 2>/dev/null || true
            fi
            ;;
        zypper)
            local pkgs=(zsh git curl screen jq fontconfig)
            if [ "$IS_ROOT" = true ]; then
                zypper install -y "${pkgs[@]}" 2>/dev/null || true
            elif command -v sudo >/dev/null 2>&1; then
                sudo zypper install -y "${pkgs[@]}" 2>/dev/null || true
            fi
            ;;
        apk)
            local pkgs=(zsh git curl screen jq fontconfig)
            if [ "$IS_ROOT" = true ]; then
                apk add --no-cache "${pkgs[@]}" 2>/dev/null || true
            elif command -v sudo >/dev/null 2>&1; then
                sudo apk add --no-cache "${pkgs[@]}" 2>/dev/null || true
            fi
            ;;
        brew)
            brew install zsh git curl screen jq 2>/dev/null || true
            ;;
        *)
            warn "No supported package manager detected. Please ensure zsh, git, and curl are installed."
            ;;
    esac
}

install_packages
success "Package dependency check complete."

# ------------------------------------------------------------------------------
# 2. Install Nerd Fonts, Symbols & Emojis (, status icons & color emojis)
# ------------------------------------------------------------------------------
FONT_BASE_DIR="$HOME/.local/share/fonts"
NERD_DIR="$FONT_BASE_DIR/NerdFonts"
EMOJI_DIR="$FONT_BASE_DIR/Emoji"
mkdir -p "$NERD_DIR" "$EMOJI_DIR"

if [ ! -f "$NERD_DIR/FiraCodeNerdFont-Regular.ttf" ] && [ ! -f "$FONT_BASE_DIR/FiraCodeNerdFont-Regular.ttf" ]; then
    info "Installing FiraCode Nerd Font (Regular)..."
    curl -fsSL -o "$NERD_DIR/FiraCodeNerdFont-Regular.ttf" \
        "https://raw.githubusercontent.com/ryanoasis/nerd-fonts/master/patched-fonts/FiraCode/Regular/FiraCodeNerdFont-Regular.ttf" 2>/dev/null || true
fi

if [ ! -f "$NERD_DIR/SymbolsNerdFont-Regular.ttf" ] && [ ! -f "$NERD_DIR/SymbolsNerdFontMono-Regular.ttf" ]; then
    info "Installing Symbols Nerd Font (universal glyphs & icons)..."
    curl -fsSL -o "$NERD_DIR/SymbolsNerdFont-Regular.ttf" \
        "https://raw.githubusercontent.com/ryanoasis/nerd-fonts/master/patched-fonts/NerdFontsSymbolsOnly/SymbolsNerdFont-Regular.ttf" 2>/dev/null || true
fi

if [ ! -f "$EMOJI_DIR/NotoColorEmoji.ttf" ] && [ ! -f "/usr/share/fonts/truetype/noto/NotoColorEmoji.ttf" ]; then
    info "Installing Google Noto Color Emoji font..."
    curl -fsSL -o "$EMOJI_DIR/NotoColorEmoji.ttf" \
        "https://raw.githubusercontent.com/google/fonts/main/ofl/notocoloremoji/NotoColorEmoji-Regular.ttf" 2>/dev/null || true
fi

# Ensure fontconfig fallback mapping
mkdir -p "$HOME/.config/fontconfig"
if [ ! -f "$HOME/.config/fontconfig/fonts.conf" ]; then
    cat << 'EOF' > "$HOME/.config/fontconfig/fonts.conf"
<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
    <alias>
        <family>monospace</family>
        <prefer>
            <family>FiraCode Nerd Font</family>
            <family>Fira Code</family>
            <family>Symbols Nerd Font</family>
            <family>Noto Color Emoji</family>
            <family>FontAwesome</family>
        </prefer>
    </alias>
</fontconfig>
EOF
fi

if command -v fc-cache >/dev/null 2>&1; then
    fc-cache -f "$FONT_BASE_DIR" >/dev/null 2>&1 || true
fi
success "Nerd Fonts, Symbols and Emojis configured."

# ------------------------------------------------------------------------------
# 3. Backup Existing Dotfiles
# ------------------------------------------------------------------------------
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="$HOME/.profile_backup_$TIMESTAMP"
mkdir -p "$BACKUP_DIR"
info "Backing up existing dotfiles to $BACKUP_DIR..."

for f in .zshrc .bashrc .screenrc .screen .config/neowofetch .oh-my-zsh/custom/themes/w4ttz.zsh-theme; do
    if [ -e "$HOME/$f" ]; then
        mkdir -p "$BACKUP_DIR/$(dirname "$f")"
        cp -a "$HOME/$f" "$BACKUP_DIR/$f" 2>/dev/null || true
    fi
done
success "Existing configurations backed up safely."

# ------------------------------------------------------------------------------
# 4. Install Oh My Zsh (Unattended)
# ------------------------------------------------------------------------------
if [ ! -d "$HOME/.oh-my-zsh" ]; then
    info "Installing Oh My Zsh (unattended)..."
    RUNZSH=no CHSH=no KEEP_ZSHRC=yes sh -c \
        "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended
    success "Oh My Zsh installed successfully."
else
    success "Oh My Zsh directory (~/.oh-my-zsh) already present."
fi

ZSH_CUSTOM="${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}"

# ------------------------------------------------------------------------------
# 5. Install Custom Oh-My-Zsh Plugins
# ------------------------------------------------------------------------------
mkdir -p "$ZSH_CUSTOM/plugins"

if [ ! -d "$ZSH_CUSTOM/plugins/zsh-autosuggestions" ]; then
    info "Cloning zsh-autosuggestions plugin..."
    git clone --depth 1 https://github.com/zsh-users/zsh-autosuggestions.git \
        "$ZSH_CUSTOM/plugins/zsh-autosuggestions" 2>/dev/null || true
fi

if [ ! -d "$ZSH_CUSTOM/plugins/zsh-syntax-highlighting" ]; then
    info "Cloning zsh-syntax-highlighting plugin..."
    git clone --depth 1 https://github.com/zsh-users/zsh-syntax-highlighting.git \
        "$ZSH_CUSTOM/plugins/zsh-syntax-highlighting" 2>/dev/null || true
fi
success "Oh-My-Zsh plugins configured."

# ------------------------------------------------------------------------------
# 6. Deploy Custom Oh-My-Zsh Theme: w4ttz.zsh-theme
# ------------------------------------------------------------------------------
info "Deploying custom theme (w4ttz.zsh-theme) with '' prompt & Ctrl+P toggle..."
mkdir -p "$ZSH_CUSTOM/themes"

cat << 'EOF' > "$ZSH_CUSTOM/themes/w4ttz.zsh-theme"
# ==============================================================================
# w4ttz Custom Oh-My-Zsh Theme
# Features:
#   - Signature prompt glyph: %n%m
#   - Root vs standard user dynamic color coding
#   - One-line & Two-line toggle via Ctrl+P
#   - Dynamic terminal window title updates
# ==============================================================================

# Enable command substitution in prompt
setopt promptsubst

# Set variable identifying chroot
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

configure_w4ttz_prompt() {
    case "$PROMPT_ALTERNATIVE" in
        twoline)
            PROMPT=$'%F{%(#.blue.green)}┌──${debian_chroot:+($debian_chroot)─}${VIRTUAL_ENV:+($(basename $VIRTUAL_ENV))─}(%B%F{%(#.red.blue)}%n'$'%m%b%F{%(#.blue.green)})-[%B%F{reset}%(6~.%-1~/…/%4~.%5~)%b%F{%(#.blue.green)}]\n└─%B%(#.%F{red}#.%F{blue}$)%b%F{reset} '
            RPROMPT=
            ;;
        oneline|*)
            PROMPT=$'${debian_chroot:+($debian_chroot)}${VIRTUAL_ENV:+($(basename $VIRTUAL_ENV))}%B%F{%(#.red.blue)}%n%m%b%F{reset}:%B%F{%(#.blue.green)}%~%b%F{reset}%(#.#.$) '
            RPROMPT=
            ;;
    esac
}

# Default prompt mode
PROMPT_ALTERNATIVE='oneline'
NEWLINE_BEFORE_PROMPT=yes

configure_w4ttz_prompt

# Ctrl+P hotkey toggles between oneline and twoline prompt modes
toggle_w4ttz_prompt() {
    if [ "$PROMPT_ALTERNATIVE" = "oneline" ]; then
        PROMPT_ALTERNATIVE="twoline"
    else
        PROMPT_ALTERNATIVE="oneline"
    fi
    configure_w4ttz_prompt
    zle reset-prompt
}
zle -N toggle_w4ttz_prompt
bindkey '^P' toggle_w4ttz_prompt

# Dynamic terminal title
case "$TERM" in
    xterm*|rxvt*|Eterm|aterm|kterm|gnome*|alacritty)
        TERM_TITLE=$'\e]0;${debian_chroot:+($debian_chroot)}${VIRTUAL_ENV:+($(basename $VIRTUAL_ENV))}%n%m: %~\a'
        ;;
esac

precmd() {
    print -Pnr -- "$TERM_TITLE"
    if [ "$NEWLINE_BEFORE_PROMPT" = "yes" ]; then
        if [ -z "$_NEW_LINE_BEFORE_PROMPT" ]; then
            _NEW_LINE_BEFORE_PROMPT=1
        else
            print ""
        fi
    fi
}
EOF
success "Custom theme created at $ZSH_CUSTOM/themes/w4ttz.zsh-theme."

# ------------------------------------------------------------------------------
# 7. Screen Configuration (~/.screenrc & ~/.screen/.screen)
# ------------------------------------------------------------------------------
info "Writing Screen configuration (auto-logging, 10,000-line scrollback, mouse wheel fix)..."
mkdir -p "$HOME/.screen"

cat << 'EOF' > "$HOME/.screenrc"
source ~/.screen/.screen
EOF

cat << 'EOF' > "$HOME/.screen/.screen"
# Enable auto-logging on start (-L)
deflog on

# Set default logfile path and timestamped file name inside ~/.screen/
logfile ~/.screen/screenlog_%y%m%d-%H%M%S.log

# Increase scrollback buffer lines
defscrollback 10000

# Tell screen to disable alternate screen switching so mouse wheel/scrollbars work natively
termcapinfo xterm* ti@:te@
termcapinfo rxvt* ti@:te@
EOF
success "Screen configured."

# ------------------------------------------------------------------------------
# 8. Neowofetch Aesthetic Banner Utility & Configuration
# ------------------------------------------------------------------------------
info "Configuring Neowofetch / Neofetch banner and icon layout..."
mkdir -p "$HOME/.local/bin"
mkdir -p "$HOME/.config/neowofetch"

if ! command -v neowofetch >/dev/null 2>&1; then
    if command -v neofetch >/dev/null 2>&1; then
        ln -sf "$(command -v neofetch)" "$HOME/.local/bin/neowofetch"
    else
        info "Downloading standalone neowofetch..."
        curl -fsSL "https://raw.githubusercontent.com/hykilpikonna/hyfetch/master/neofetch" -o "$HOME/.local/bin/neowofetch" 2>/dev/null || true
        if [ -s "$HOME/.local/bin/neowofetch" ]; then
            chmod +x "$HOME/.local/bin/neowofetch"
        fi
    fi
fi

cat << 'EOF' > "$HOME/.config/neowofetch/config.conf"
# Neowofetch Aesthetic Configuration with Custom Icons
print_info() {
    info title
    info "ﭛ" local_ip
    info "" public_ip
    info underline
    info "" distro
    info "" model
    info "" cpu
    info "" disk
    info "" memory
    info "" bluetooth
    info "" python_ver
    info "" java_ver
    info "" node_ver
    info "" shell
    info "⏻" uptime
    info cols
}

title_fqdn="on"
kernel_shorthand="on"
distro_shorthand="tiny"
os_arch="off"
uptime_shorthand="tiny"
memory_percent="on"
memory_unit="gib"
mem_precision=2
package_managers="tiny"
package_separate="off"
package_minimal=""
shell_path="on"
shell_version="on"
editor_path="off"
editor_version="off"
speed_type="bios_limit"
speed_shorthand="on"
cpu_brand="on"
cpu_speed="on"
cpu_cores="on"
cpu_temp="F"
gpu_brand="off"
refresh_rate="off"
gtk_shorthand="on"
gtk2="on"
gtk3="on"
qt="off"
public_ip_host="https://api.ipify.org"
public_ip_timeout=2
local_ip_interface=('auto')
de_version="off"
disk_show=('/')
disk_subtitle="none"
disk_percent="on"
music_player="spotify"
song_format="%artist% - %album% - %title%"
song_shorthand="on"
mpc_args=()
colors=(4 6 1 8 8 6)
bold="on"
underline_enabled="on"
underline_char=""
separator=""
block_range=(0 15)
color_blocks="on"
block_width=3
block_height=1
col_offset="auto"
bar_char_elapsed=""
bar_char_total=""
bar_border="on"
bar_length=15
bar_color_elapsed="6"
bar_color_total="8"
memory_display="bar"
battery_display="off"
disk_display="bar"
image_backend="ascii"
image_source="auto"
ascii_distro="kali_small"
ascii_colors=(4 6 1 8 8 6)
ascii_bold="on"
image_loop="off"
thumbnail_dir="${XDG_CACHE_HOME:-${HOME}/.cache}/thumbnails/neowofetch"
crop_mode="normal"
crop_offset="center"
image_size="20%"
catimg_size="2"
gap=3
yoffset=0
xoffset=0
background_color=
stdout="off"
EOF

# Link neofetch config as well for seamless fallback
mkdir -p "$HOME/.config/neofetch"
ln -sf "$HOME/.config/neowofetch/config.conf" "$HOME/.config/neofetch/config.conf" 2>/dev/null || true
success "Banner aesthetics configured."

# ------------------------------------------------------------------------------
# 9. Generate ~/.zshrc (Oh-My-Zsh + Custom Aesthetics + Aliases Suite)
# ------------------------------------------------------------------------------
info "Writing ~/.zshrc with Oh My Zsh theme, plugins, and custom aliases..."

cat << 'EOF' > "$HOME/.zshrc"
# ~/.zshrc - Configured with Oh My Zsh and Custom Aesthetics

# Automatically start or reconnect to a persistent screen session over SSH
if [[ -n "$SSH_CONNECTION" ]] && [[ -z "$STY" ]]; then
    screen -R -D "ssh_session_${$}"
fi

# Path to your Oh My Zsh installation
export ZSH="$HOME/.oh-my-zsh"

# Set custom theme
ZSH_THEME="w4ttz"

# Enable Oh-My-Zsh plugins
plugins=(
    git
    zsh-autosuggestions
    zsh-syntax-highlighting
)

# User-space fallback for plugins if not in Oh-My-Zsh
if [ -d "$ZSH" ]; then
    source "$ZSH/oh-my-zsh.sh"
fi

# Shell Options
setopt autocd              # change directory just by typing its name
setopt interactivecomments # allow comments in interactive mode
setopt magicequalsubst     # enable filename expansion for arguments of the form 'anything=expression'
setopt nonomatch           # hide error message if there is no match for pattern
setopt notify              # report background jobs immediately
setopt numericglobsort     # sort filenames numerically
setopt promptsubst         # enable command substitution in prompt

WORDCHARS=${WORDCHARS//\/} # Don't consider '/' part of words
PROMPT_EOL_MARK=""         # Hide EOL mark ('%')

# Keybindings
bindkey -e                                        # emacs key bindings
bindkey ' ' magic-space                           # history expansion on space
bindkey '^U' backward-kill-line                   # ctrl + U
bindkey '^[[3;5~' kill-word                       # ctrl + Supr
bindkey '^[[3~' delete-char                       # delete
bindkey '^[[1;5C' forward-word                    # ctrl + ->
bindkey '^[[1;5D' backward-word                   # ctrl + <-
bindkey '^[[5~' beginning-of-buffer-or-history    # page up
bindkey '^[[6~' end-of-buffer-or-history          # page down
bindkey '^[[H' beginning-of-line                  # home
bindkey '^[[F' end-of-line                        # end
bindkey '^[[Z' undo                               # shift + tab undo last action

# History configuration
HISTFILE=~/.zsh_history
HISTSIZE=5000
SAVEHIST=10000
setopt hist_expire_dups_first
setopt hist_ignore_dups
setopt hist_ignore_space
setopt hist_verify

alias history="history 0"
TIMEFMT=$'\nreal\t%E\nuser\t%U\nsys\t%S\ncpu\t%P'

# Syntax Highlighting Palette
typeset -A ZSH_HIGHLIGHT_STYLES 2>/dev/null || true
ZSH_HIGHLIGHT_HIGHLIGHTERS=(main brackets pattern)
ZSH_HIGHLIGHT_STYLES[default]=none
ZSH_HIGHLIGHT_STYLES[unknown-token]=underline
ZSH_HIGHLIGHT_STYLES[reserved-word]=fg=cyan,bold
ZSH_HIGHLIGHT_STYLES[suffix-alias]=fg=green,underline
ZSH_HIGHLIGHT_STYLES[global-alias]=fg=green,bold
ZSH_HIGHLIGHT_STYLES[precommand]=fg=green,underline
ZSH_HIGHLIGHT_STYLES[commandseparator]=fg=blue,bold
ZSH_HIGHLIGHT_STYLES[autodirectory]=fg=green,underline
ZSH_HIGHLIGHT_STYLES[path]=bold
ZSH_HIGHLIGHT_STYLES[globbing]=fg=blue,bold
ZSH_HIGHLIGHT_STYLES[history-expansion]=fg=blue,bold
ZSH_HIGHLIGHT_STYLES[single-hyphen-option]=fg=green
ZSH_HIGHLIGHT_STYLES[double-hyphen-option]=fg=green
ZSH_HIGHLIGHT_STYLES[single-quoted-argument]=fg=yellow
ZSH_HIGHLIGHT_STYLES[double-quoted-argument]=fg=yellow
ZSH_HIGHLIGHT_STYLES[dollar-quoted-argument]=fg=yellow
ZSH_HIGHLIGHT_STYLES[arg0]=fg=cyan
ZSH_HIGHLIGHT_STYLES[bracket-level-1]=fg=blue,bold
ZSH_HIGHLIGHT_STYLES[bracket-level-2]=fg=green,bold
ZSH_HIGHLIGHT_STYLES[bracket-level-3]=fg=magenta,bold
ZSH_HIGHLIGHT_STYLES[bracket-level-4]=fg=yellow,bold
ZSH_HIGHLIGHT_STYLES[bracket-level-5]=fg=cyan,bold
ZSH_HIGHLIGHT_STYLES[cursor-matchingbracket]=standout

# Autosuggestions Styling
ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE='fg=#999'

# Color support for ls and less
if [ -x /usr/bin/dircolors ]; then
    test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
    export LS_COLORS="$LS_COLORS:ow=30;44:"
    alias ls='ls --color=auto'
    alias grep='grep --color=auto'
    alias fgrep='fgrep --color=auto'
    alias egrep='egrep --color=auto'
    alias _diff='diff --color=auto'

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

# ==============================================================================
# Aliases & Functions Suite
# ==============================================================================

# General / Navigation
alias _s='sudo'
alias _su='sudo su -'
alias _al='alias'
alias _als='alist'
alias _aset='alias-set'
alias ltr='ls -lahtr'
alias la='ls -Aa'
alias ll='ls -la'
alias l='ls -lah'
alias c='clear'
alias _.='cd ..'
alias _..='cd ../../'
alias _...='cd ../../../'
alias _....='cd ../../../../'
alias _.....='cd ../../../../../'
alias _n='nano -l'
alias _nb='_n ~/.zshrc'
alias _eb='exec zsh'
alias python='python3'
alias _py='python3'
alias _pi='pip install'
alias _p3='pip3 install'
alias _px='pipx install'
alias _pva='_py -m venv ~/venv && source ~/venv/bin/activate'
alias _pvd='deactivate'
alias _ct='cat -n'
alias _exp='export PATH="$1:$PATH"'
alias _lu='_s lsusb'

# Package Management (apt wrapper)
alias _ag='_s apt'
alias _ai='_ag install -y'
alias _au='_ag update && apt upgrade -y'
alias _as="_ag search '$1'"
alias _ar='_ag remove'
alias _aa='_ag -y autoremove'

# Grep helpers
alias _gp='grep -P'
alias _go='grep -Pio'
alias _gv='grep -Pv'
alias _ge='grep -E'
alias psgrep="_s ps aux | _gp '$1' | _gv grep"
alias _psg='psgrep'

# Recon & Security Tooling
alias _fs='_s fsociety'
alias _zph='_s zphisher'
alias dsniff='_s /usr/sbin/dsniff'
alias _dsnf='dsniff'
alias msf='_s /usr/bin/msfconsole'
alias msfconsole='_s /usr/bin/msfconsole'
alias _msc='msfconsole'
alias _shlk='sherlock'
alias tcpdump='_s /usr/bin/tcpdump'
alias _tdmp='tcpdump $1 -l -w '
alias nmap='_s /usr/bin/nmap'
alias netcat='_s /usr/bin/ncat'
alias arp-scan='_s /usr/sbin/arp-scan'
alias _nmq='nmap -sSV -T4 $1'
alias nping='_s /usr/bin/nping'
alias ndif='_s /usr/bin/ndiff'
alias ettercap='_s /usr/bin/ettercap'

# Network & DNS
alias _dg='dig -t'
alias _dga='_dg A $1 +short'
alias _dga.='_dg AAAA $1 +short'
alias _dgn='_dg NS $1 +short'
alias _dgt='_dg TXT $1 +short'
alias _dgc='_dg CNAME $1 +short'
alias _dgm='_dg MX $1 +short'
alias _dgx='dig -x $1 +short'
alias _dgp='dig-ptr'
alias _shr='ssh root@$1'
alias _sh.='ssh $1@$2'
alias _shkg='ssh-keygen -t rsa'
alias _shkc='ssh-copy-id $1@$2'
alias _iw='_s iw list'
alias _pngc='ping -c $1 -s 2 $2'
alias _trt='_s traceroute'
alias _trtm='_trt -m $1 $2'
alias arping='_s /usr/sbin/arping'
alias _apng='arping'
alias _idb='_ndb'
alias _edb='entdb'
alias _entlu='entity_lookup'

# Recon Functions
function entity_lookup() {
    sudo grep -Pi "$1" /root/.local/shodan/entitydb/entitydb.shodan 2>/dev/null
}

function _edbips() {
    sudo entdb "$1" "$2" 2>/dev/null | head -20 | grep -Po '(?<=name\"\:\ \").*(?=\")'
    sudo entdb "$1" "$2" 2>/dev/null | grep -Po '(?<=x\"\:\ \")(\d{1,3}\.){3}\d{1,3}\/\d{1,2}' | sort -u
}

function _edbfi() {
    sudo entdb "$1" "$2" 2>/dev/null | head -20 | grep -Po '(?<=name\"\:\ \").*(?=\")'
    sudo entdb "$1" "$2" 2>/dev/null | grep -Po "(?<=\")revenue(?=\"\:\ \").*(?=\,)|(?<=\")net_income(?=\"\:).*(?=\,)"
}

function _ndb() {
    curl -s "https://internetdb.shodan.io/$1" --stderr - | jq .
}

function ipaddr() {
    echo "::ipaddr::"
    if command -v ip >/dev/null 2>&1; then
        ip -o -4 addr show | awk '{print $4}' | cut -d/ -f1 | sort -u
    else
        ifconfig 2>/dev/null | grep -Po "(\d{1,3}\.){3}\d{1,3}" | grep -Pv '(255|0|254)(\.|$)' | sort -u
    fi
    echo ""
    echo "::ifconfig.me::"
    curl -s ifconfig.me
    echo ""
}

function dig-ptr() {
    local _rvip="dig -x $1 +short"
    local _ptra="dig -t A $_rvip +short"
    echo -e "$_ptra"
    whois "$_ptra" 2>/dev/null | grep -Pio "Registrar\:.*$" | head -1
}

# Floating Aliases Helpers
function alist() {
    grep -P "^alias\ (\w|_).*$" ~/.zshrc
}

function alias-set() {
    local _ptrn="$1"
    local _alas="$2"
    local _al_s="$3"
    sed -i "/$_ptrn/a\alias $_alas='$_al_s'" ~/.zshrc
}

# AI CLI Helpers (Configure your API keys in environment or ~/.zprofile)
function gpt-prompt() {
    local prompt="Please: "
    if [ -n "$1" ]; then
       prompt="$1"
       shift
    fi
    sgpt "$prompt $*"
}

function dgpt() {
    local key="${OPENAI_API_KEY:-}"
    if [ -z "$key" ]; then
        echo "Error: Set OPENAI_API_KEY in your environment to use dgpt."
        return 1
    fi
    debgpt --openai_api_key "$key" --openai-model "gpt-4o-mini" "$@"
}

function ddsk() {
    local key="${DEEPSEEK_API_KEY:-}"
    if [ -z "$key" ]; then
        echo "Error: Set DEEPSEEK_API_KEY in your environment to use ddsk."
        return 1
    fi
    debgpt --deepseek_api_key "$key" --deepseek-model "V3" "$@"
}

function dgai() {
    local key="${GEMINI_API_KEY:-}"
    if [ -z "$key" ]; then
        echo "Error: Set GEMINI_API_KEY in your environment to use dgai."
        return 1
    fi
    debgpt --google_api_key "$key" --google-model "gemini-2.5-flash" "$@"
}

# Ensure ~/.local/bin is in PATH
export PATH="$HOME/.local/bin:$PATH"

# Launch Banner
clear
if command -v neowofetch >/dev/null 2>&1; then
    neowofetch
elif command -v neofetch >/dev/null 2>&1; then
    neofetch
fi
EOF
success "Configured ~/.zshrc."

# ------------------------------------------------------------------------------
# 10. Bash Counterpart (~/.bashrc)
# ------------------------------------------------------------------------------
info "Writing ~/.bashrc prompt counterpart..."

cat << 'EOF' > "$HOME/.bashrc"
# ~/.bashrc - Interactive Bash counterpart matching aesthetics

case $- in
    *i*) ;;
      *) return;;
esac

if [[ -n "$SSH_CONNECTION" ]] && [[ -z "$STY" ]]; then
    screen -R -D "ssh_session_${$}"
fi

HISTCONTROL=ignoreboth
shopt -s histappend
HISTSIZE=5000
HISTFILESIZE=10000
shopt -s checkwinsize

case "$TERM" in
    xterm-color|*-256color) color_prompt=yes;;
esac
force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
        color_prompt=yes
    fi
fi

PROMPT_ALTERNATIVE='oneline'
NEWLINE_BEFORE_PROMPT=yes

if [ "$color_prompt" = yes ]; then
    VIRTUAL_ENV_DISABLE_PROMPT=1
    prompt_color='\[\033[;32m\]'
    info_color='\[\033[1;34m\]'
    if [ "$EUID" -eq 0 ]; then
        prompt_color='\[\033[;94m\]'
        info_color='\[\033[1;31m\]'
    fi
    case "$PROMPT_ALTERNATIVE" in
        twoline)
            PS1=$prompt_color'┌──${debian_chroot:+($debian_chroot)──}${VIRTUAL_ENV:+(\[\033[0;1m\]$(basename $VIRTUAL_ENV)'$prompt_color')}('$info_color'\u\h'$prompt_color')-[\[\033[0;1m\]\w'$prompt_color']\n'$prompt_color'└─'$info_color'\$\[\033[0m\] ';;
        oneline|*)
            PS1='${VIRTUAL_ENV:+($(basename $VIRTUAL_ENV)) }${debian_chroot:+($debian_chroot)}'$info_color'\u\h\[\033[00m\]:'$prompt_color'\[\033[01m\]\w\[\033[00m\]\$ ';;
    esac
    unset prompt_color info_color
else
    PS1='${debian_chroot:+($debian_chroot)}\u\h:\w\$ '
fi
unset color_prompt force_color_prompt

if [ -x /usr/bin/dircolors ]; then
    test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
    alias ls='ls --color=auto'
    alias grep='grep --color=auto'
fi

# Quick navigation & aliases
alias _s='sudo'
alias _su='sudo su -'
alias ltr='ls -lahtr'
alias la='ls -Aa'
alias ll='ls -la'
alias l='ls -lah'
alias c='clear'
alias _.='cd ..'
alias _..='cd ../../'
alias _...='cd ../../../'
alias _n='nano -l'
alias _nb='_n ~/.bashrc'
alias _eb='source ~/.bashrc'
alias python='python3'
alias _py='python3'

export PATH="$HOME/.local/bin:$PATH"

clear
if command -v neowofetch >/dev/null 2>&1; then
    neowofetch
elif command -v neofetch >/dev/null 2>&1; then
    neofetch
fi
EOF
success "Configured ~/.bashrc."

# ------------------------------------------------------------------------------
# 11. Set Zsh as Default Shell
# ------------------------------------------------------------------------------
info "Checking default login shell..."
if command -v zsh >/dev/null 2>&1; then
    ZSH_PATH=$(command -v zsh)
    CURRENT_SHELL=$(basename "$SHELL")
    if [ "$CURRENT_SHELL" != "zsh" ]; then
        info "Changing default login shell to $ZSH_PATH..."
        if [ "$IS_ROOT" = true ]; then
            chsh -s "$ZSH_PATH" "${SUDO_USER:-$USER}" 2>/dev/null || true
            success "Default shell set to $ZSH_PATH for ${SUDO_USER:-$USER}."
        elif command -v chsh >/dev/null 2>&1; then
            if chsh -s "$ZSH_PATH" 2>/dev/null; then
                success "Default shell changed to $ZSH_PATH."
            elif command -v sudo >/dev/null 2>&1; then
                sudo chsh -s "$ZSH_PATH" "$USER" 2>/dev/null || warn "Could not automatically set default shell. Run: chsh -s $ZSH_PATH"
            else
                warn "Could not change default shell automatically. Please run: chsh -s $ZSH_PATH"
            fi
        fi
    else
        success "Zsh is already your default shell."
    fi
else
    warn "Zsh executable not found in PATH."
fi

# ------------------------------------------------------------------------------
# 12. Completion & Instructions
# ------------------------------------------------------------------------------
echo ""
echo -e "${GREEN}${BOLD}============================================================${NC}"
echo -e "${GREEN}${BOLD}    Terminal Aesthetics & Oh-My-Zsh Successfully Setup!     ${NC}"
echo -e "${GREEN}${BOLD}============================================================${NC}"
echo -e "To activate your new shell aesthetics immediately, run:"
echo -e "  ${YELLOW}exec zsh${NC}"
echo ""
echo -e "Included features:"
echo -e "  - Prompt glyph:      ${CYAN}usernamehostname${NC}"
echo -e "  - Prompt toggle:     Press ${YELLOW}Ctrl+P${NC} to switch between single-line & two-line modes"
echo -e "  - Oh-My-Zsh theme:   ${CYAN}w4ttz${NC} (~/.oh-my-zsh/custom/themes/w4ttz.zsh-theme)"
echo -e "  - OMZ Plugins:       ${CYAN}git, zsh-autosuggestions, zsh-syntax-highlighting${NC}"
echo -e "  - Banner utility:    ${CYAN}neowofetch${NC} with custom status bar telemetry"
echo -e "  - Screen session:    Auto-logging, 10k scrollback, SSH auto-attach"
echo -e "  - Dotfiles backup:   ${CYAN}$BACKUP_DIR${NC}"
echo ""
