#!/usr/bin/env bash
# ==============================================================================
# Automated installer - modern terminal environment
# Supports: Fedora/RHEL, Debian/Ubuntu (and derivatives), macOS (Homebrew / Zerobrew)
# Architectures: x86_64 and aarch64 (ARM)
# Optional environment flags: SKIP_GIT_CONFIG=1, SKIP_FONT=1, DRY_RUN=1
# Optional version pins: YAZI_VERSION, ZELLIJ_VERSION, LAZYGIT_VERSION,
#                        STARSHIP_VERSION, KUBECTL_VERSION, KUBECTX_VERSION,
#                        LAZYDOCKER_VERSION, KUBECONFORM_VERSION
# DRY_RUN=1 only prints what would be installed or written; nothing is changed.
# ==============================================================================

set -euo pipefail

GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[OK]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

DRY_RUN="${DRY_RUN:-}"
[ -n "$DRY_RUN" ] && log_warn "DRY_RUN is set: no changes will be made"

ARCH=$(uname -m)
OS="$(uname -s)"

case "$ARCH" in
    x86_64|amd64) ARCH_KEY="x86_64"; LG_ARCH="x86_64"; K8S_ARCH="amd64" ;;
    aarch64|arm64) ARCH_KEY="aarch64"; LG_ARCH="arm64"; K8S_ARCH="arm64" ;;
    *) log_error "Unsupported architecture: $ARCH"; exit 1 ;;
esac

log_info "Detecting operating system and architecture..."
log_info "OS: $OS | Architecture: $ARCH"

TMP_ROOT="$(mktemp -d)"
trap 'rm -rf "$TMP_ROOT"' EXIT

SITE_FUNCTIONS="/usr/local/share/zsh/site-functions"

# --- Helpers ---------------------------------------------------------------

# Runs a command, or only prints it when DRY_RUN is set.
run() {
    if [ -n "$DRY_RUN" ]; then
        log_info "[dry-run] $*"
    else
        "$@"
    fi
}

as_root() {
    if [ "$(id -u)" -eq 0 ]; then
        run "$@"
    else
        run sudo "$@"
    fi
}

# Writes stdin to the given file, or only reports it when DRY_RUN is set.
write_file() {
    if [ -n "$DRY_RUN" ]; then
        log_info "[dry-run] would write $1"
        cat > /dev/null
    else
        cat > "$1"
    fi
}

backup_file() {
    if [ -z "$DRY_RUN" ] && [ -f "$1" ]; then
        cp -p "$1" "$1.backup.$(date +%s)"
        log_info "Backup created: $1.backup.*"
    fi
}

download() {
    curl -fsSL --retry 3 -o "$2" "$1"
}

# Latest GitHub release tag of a repo, or the given fallback when the API fails.
latest_tag() {
    local tag
    tag=$(curl -fsSL "https://api.github.com/repos/$1/releases/latest" 2>/dev/null \
        | sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p' | head -n1) || true
    echo "${tag:-$2}"
}

# Hash listed at <url>: the line for <name> in a checksums file, or the first
# field when no name is given (single-hash files).
fetch_hash() {
    local url="$1" name="${2:-}" body
    body="$(curl -fsSL --retry 3 "$url")" || return 1
    if [ -n "$name" ]; then
        awk -v n="$name" '$2 == n { print $1; exit }' <<< "$body"
    else
        awk 'NR == 1 { print $1 }' <<< "$body"
    fi
}

# Aborts unless the SHA-256 of <file> matches the one published at <url>.
verify_download() {
    local file="$1" url="$2" name="${3:-}" expected actual
    expected="$(fetch_hash "$url" "$name" || true)"
    if [ -z "$expected" ]; then
        log_error "Could not read the checksum from $url"
        exit 1
    fi
    actual="$(sha256sum "$file" | cut -d' ' -f1)"
    if [ "$actual" != "$expected" ]; then
        log_error "Checksum mismatch for $(basename "$file") (expected $expected, got $actual)"
        exit 1
    fi
}

PKG_KIND=""
PKG_INSTALL_CMD=()
PKG_NEEDS_ROOT=0

is_installed() {
    case "$PKG_KIND" in
        rpm) rpm -q "$1" >/dev/null 2>&1 ;;
        deb) dpkg -s "$1" >/dev/null 2>&1 ;;
        *) return 1 ;;
    esac
}

run_pkg_install() {
    if [ "$PKG_NEEDS_ROOT" -eq 1 ]; then
        as_root "${PKG_INSTALL_CMD[@]}" "$@"
    else
        run "${PKG_INSTALL_CMD[@]}" "$@"
    fi
}

# Installs only the missing packages. If the batch fails (e.g. one package is not
# in the repos), retries one by one so a single missing package never blocks the rest.
install_packages() {
    local missing=() pkg
    for pkg in "$@"; do
        if ! is_installed "$pkg"; then
            missing+=("$pkg")
        fi
    done
    if [ "${#missing[@]}" -eq 0 ]; then
        log_info "All packages are already installed"
        return 0
    fi
    log_info "Installing: ${missing[*]}"
    if run_pkg_install "${missing[@]}"; then
        return 0
    fi
    log_warn "Batch install failed; retrying package by package..."
    for pkg in "${missing[@]}"; do
        run_pkg_install "$pkg" || log_warn "Could not install '$pkg' (skipped)"
    done
}

# Creates /usr/local/bin/<alias> when the distro ships the tool under another name.
link_alias() {
    local src
    if command -v "$2" >/dev/null 2>&1; then
        return 0
    fi
    src="$(command -v "$1" 2>/dev/null || true)"
    if [ -n "$src" ]; then
        as_root ln -sf "$src" "/usr/local/bin/$2"
    fi
}

# Runs the installer function <fn> unless <tool> is already available.
ensure_tool() {
    if command -v "$1" >/dev/null 2>&1; then
        return 0
    fi
    if [ -n "$DRY_RUN" ]; then
        log_info "[dry-run] would install $1"
        return 0
    fi
    "$2"
}

# --- Binary installers (Linux only; each verifies its download when upstream publishes a checksum) ---

install_starship() {
    local ver dir="$TMP_ROOT/starship" target="${ARCH_KEY}-unknown-linux-musl"
    log_info "Installing Starship prompt..."
    ver="${STARSHIP_VERSION:-$(latest_tag starship/starship v1.27.0)}"
    mkdir -p "$dir"
    download "https://github.com/starship/starship/releases/download/${ver}/starship-${target}.tar.gz" "$dir/starship.tar.gz"
    verify_download "$dir/starship.tar.gz" "https://github.com/starship/starship/releases/download/${ver}/starship-${target}.tar.gz.sha256"
    tar -xzf "$dir/starship.tar.gz" -C "$dir"
    as_root install -m 755 "$dir/starship" /usr/local/bin/
}

install_yazi() {
    local ver dir="$TMP_ROOT/yazi" target="${ARCH_KEY}-unknown-linux-musl" comp
    log_info "Installing Yazi..."
    log_warn "Yazi publishes no checksums; the download cannot be verified"
    ver="${YAZI_VERSION:-$(latest_tag sxyazi/yazi v26.9.1)}"
    mkdir -p "$dir"
    download "https://github.com/sxyazi/yazi/releases/download/${ver}/yazi-${target}.zip" "$dir/yazi.zip"
    unzip -q "$dir/yazi.zip" -d "$dir" 2>/dev/null \
        || python3 -m zipfile -e "$dir/yazi.zip" "$dir"
    as_root install -m 755 "$dir/yazi-${target}/yazi" "$dir/yazi-${target}/ya" /usr/local/bin/
    as_root mkdir -p "$SITE_FUNCTIONS"
    for comp in _yazi _ya; do
        if [ -f "$dir/yazi-${target}/completions/$comp" ]; then
            as_root install -m 644 "$dir/yazi-${target}/completions/$comp" "$SITE_FUNCTIONS/"
        fi
    done
}

install_zellij() {
    local ver dir="$TMP_ROOT/zellij" target="${ARCH_KEY}-unknown-linux-musl"
    log_info "Installing Zellij multiplexer..."
    ver="${ZELLIJ_VERSION:-$(latest_tag zellij-org/zellij v0.45.1)}"
    mkdir -p "$dir"
    download "https://github.com/zellij-org/zellij/releases/download/${ver}/zellij-${target}.tar.gz" "$dir/zellij.tar.gz"
    tar -xzf "$dir/zellij.tar.gz" -C "$dir"
    # The published checksum is that of the extracted binary, not of the archive
    verify_download "$dir/zellij" "https://github.com/zellij-org/zellij/releases/download/${ver}/zellij-${target}.sha256sum"
    as_root install -m 755 "$dir/zellij" /usr/local/bin/
}

install_lazygit() {
    local tag dir="$TMP_ROOT/lazygit" asset
    log_info "Installing Lazygit..."
    tag="${LAZYGIT_VERSION:-$(latest_tag jesseduffield/lazygit v0.66.2)}"
    asset="lazygit_${tag#v}_linux_${LG_ARCH}.tar.gz"
    mkdir -p "$dir"
    download "https://github.com/jesseduffield/lazygit/releases/download/${tag}/${asset}" "$dir/lazygit.tar.gz"
    verify_download "$dir/lazygit.tar.gz" "https://github.com/jesseduffield/lazygit/releases/download/${tag}/checksums.txt" "$asset"
    tar -xzf "$dir/lazygit.tar.gz" -C "$dir"
    as_root install -m 755 "$dir/lazygit" /usr/local/bin/
}

install_kubectl() {
    local ver dir="$TMP_ROOT/kubectl"
    log_info "Installing kubectl..."
    ver="${KUBECTL_VERSION:-$(curl -fsSL https://dl.k8s.io/release/stable.txt 2>/dev/null || echo v1.37.1)}"
    mkdir -p "$dir"
    download "https://dl.k8s.io/release/${ver}/bin/linux/${K8S_ARCH}/kubectl" "$dir/kubectl"
    verify_download "$dir/kubectl" "https://dl.k8s.io/release/${ver}/bin/linux/${K8S_ARCH}/kubectl.sha256"
    as_root install -m 755 "$dir/kubectl" /usr/local/bin/
}

install_lazydocker() {
    local tag dir="$TMP_ROOT/lazydocker" asset
    log_info "Installing Lazydocker..."
    tag="${LAZYDOCKER_VERSION:-$(latest_tag jesseduffield/lazydocker v0.25.2)}"
    asset="lazydocker_${tag#v}_Linux_${LG_ARCH}.tar.gz"
    mkdir -p "$dir"
    download "https://github.com/jesseduffield/lazydocker/releases/download/${tag}/${asset}" "$dir/lazydocker.tar.gz"
    verify_download "$dir/lazydocker.tar.gz" "https://github.com/jesseduffield/lazydocker/releases/download/${tag}/checksums.txt" "$asset"
    tar -xzf "$dir/lazydocker.tar.gz" -C "$dir" lazydocker
    as_root install -m 755 "$dir/lazydocker" /usr/local/bin/
}

install_kubeconform() {
    local tag dir="$TMP_ROOT/kubeconform" asset="kubeconform-linux-${K8S_ARCH}.tar.gz"
    log_info "Installing kubeconform..."
    tag="${KUBECONFORM_VERSION:-$(latest_tag yannh/kubeconform v0.8.0)}"
    mkdir -p "$dir"
    download "https://github.com/yannh/kubeconform/releases/download/${tag}/${asset}" "$dir/kubeconform.tar.gz"
    verify_download "$dir/kubeconform.tar.gz" "https://github.com/yannh/kubeconform/releases/download/${tag}/CHECKSUMS" "$asset"
    tar -xzf "$dir/kubeconform.tar.gz" -C "$dir" kubeconform
    as_root install -m 755 "$dir/kubeconform" /usr/local/bin/
}

# kubectx and kubens ship as separate archives of the same release; installs the
# missing ones together with their zsh completions.
install_kubectx_kubens() {
    local ver dir="$TMP_ROOT/kubectx" tool asset base
    log_info "Installing kubectx and kubens..."
    ver="${KUBECTX_VERSION:-$(latest_tag ahmetb/kubectx v0.11.0)}"
    base="https://github.com/ahmetb/kubectx/releases/download/${ver}"
    mkdir -p "$dir"
    as_root mkdir -p "$SITE_FUNCTIONS"
    for tool in kubectx kubens; do
        if ! command -v "$tool" >/dev/null 2>&1; then
            asset="${tool}_${ver}_linux_${LG_ARCH}.tar.gz"
            download "$base/$asset" "$dir/$asset"
            verify_download "$dir/$asset" "$base/checksums.txt" "$asset"
            tar -xzf "$dir/$asset" -C "$dir" "$tool"
            as_root install -m 755 "$dir/$tool" /usr/local/bin/
        fi
        if [ ! -f "$SITE_FUNCTIONS/_$tool" ]; then
            download "https://raw.githubusercontent.com/ahmetb/kubectx/${ver}/completion/_${tool}.zsh" "$dir/_$tool"
            as_root install -m 644 "$dir/_$tool" "$SITE_FUNCTIONS/_$tool"
        fi
    done
}

# --- 1. Packages from the system package manager --------------------------------
PACKAGE_MANAGER=""

if [[ "$OS" == "Darwin" ]]; then
    log_info "Detected system: macOS"
    if command -v zb >/dev/null 2>&1; then
        PACKAGE_MANAGER="zb"
    elif command -v brew >/dev/null 2>&1; then
        PACKAGE_MANAGER="brew"
    else
        log_warn "Neither Homebrew nor Zerobrew is installed. Installing Zerobrew..."
        if [ -z "$DRY_RUN" ]; then
            download https://zerobrew.rs/install "$TMP_ROOT/zerobrew-install.sh"
            bash "$TMP_ROOT/zerobrew-install.sh"
        fi
        PACKAGE_MANAGER="zb"
    fi

    PKG_KIND="mac"
    PKG_INSTALL_CMD=("$PACKAGE_MANAGER" install)
    install_packages \
        zsh-autosuggestions zsh-syntax-highlighting starship chafa yazi zellij \
        bat eza btop duf ncdu ffmpeg sevenzip jq fd ripgrep fzf zoxide poppler \
        lazygit git-delta fastfetch kubernetes-cli kubectx direnv tealdeer dust procs hyperfine \
        lazydocker kubeconform

elif [[ -f /etc/os-release ]]; then
    . /etc/os-release
    log_info "Detected distribution: ${NAME:-unknown} ${VERSION_ID:-}"

    if [ "$(id -u)" -ne 0 ] && ! command -v sudo >/dev/null 2>&1; then
        log_error "sudo is required (or run as root)"
        exit 1
    fi

    FAMILY=""
    case " ${ID:-} ${ID_LIKE:-} " in
        *" fedora "*|*" rhel "*) FAMILY="fedora" ;;
        *" debian "*|*" ubuntu "*) FAMILY="debian" ;;
    esac

    case "$FAMILY" in
        fedora)
            PKG_KIND="rpm"
            PKG_NEEDS_ROOT=1
            PKG_INSTALL_CMD=(dnf install -y)
            FEDORA_PKGS=(
                zsh zsh-autosuggestions zsh-syntax-highlighting chafa bat eza btop duf ncdu
                poppler-utils 7zip jq fd-find ripgrep fzf zoxide file curl tar unzip git
                git-delta fastfetch direnv tealdeer du-dust procs hyperfine
            )
            # RPM Fusion's full ffmpeg conflicts with ffmpeg-free
            if ! command -v ffmpeg >/dev/null 2>&1; then
                FEDORA_PKGS+=(ffmpeg-free)
            fi
            install_packages "${FEDORA_PKGS[@]}"
            ;;
        debian)
            PKG_KIND="deb"
            PKG_NEEDS_ROOT=1
            PKG_INSTALL_CMD=(apt-get install -y)
            as_root apt-get update || log_warn "apt-get update failed; continuing with the existing cache"
            DEBIAN_PKGS=(
                zsh zsh-autosuggestions zsh-syntax-highlighting chafa bat eza btop duf ncdu
                poppler-utils p7zip-full jq fd-find ripgrep fzf zoxide file curl tar unzip git
                git-delta fastfetch direnv tealdeer du-dust procs hyperfine
            )
            if ! command -v ffmpeg >/dev/null 2>&1; then
                DEBIAN_PKGS+=(ffmpeg)
            fi
            install_packages "${DEBIAN_PKGS[@]}"
            # Debian/Ubuntu rename these binaries
            link_alias fdfind fd
            link_alias batcat bat
            ;;
        *)
            log_warn "Unsupported distribution (${ID:-?}). Skipping the system packages."
            ;;
    esac

    # --- Binaries not (reliably) packaged on Linux ---
    ensure_tool starship install_starship
    ensure_tool yazi install_yazi
    ensure_tool zellij install_zellij
    ensure_tool lazygit install_lazygit
    ensure_tool kubectl install_kubectl
    ensure_tool lazydocker install_lazydocker
    ensure_tool kubeconform install_kubeconform
    if ! command -v kubectx >/dev/null 2>&1 || ! command -v kubens >/dev/null 2>&1; then
        ensure_tool kubectx_kubens install_kubectx_kubens
    fi
else
    log_error "Unsupported operating system"
    exit 1
fi

# --- 2. fzf-tab plugin (not packaged anywhere) ---
FZF_TAB_DIR="$HOME/.fzf-tab"
if [ -d "$FZF_TAB_DIR/.git" ]; then
    log_info "Updating fzf-tab..."
    run git -C "$FZF_TAB_DIR" pull --ff-only --quiet || log_warn "Could not update fzf-tab"
else
    log_info "Installing fzf-tab..."
    run git clone --depth 1 --quiet https://github.com/Aloxaf/fzf-tab "$FZF_TAB_DIR" \
        || log_warn "Could not clone fzf-tab (interactive completion will be disabled)"
fi

# --- 3. Nerd Font (needed by eza icons and the Starship symbols) ---
install_nerd_font() {
    local font_dir="$HOME/.local/share/fonts/JetBrainsMonoNerdFont"
    log_info "Installing JetBrainsMono Nerd Font..."
    mkdir -p "$font_dir"
    if download "https://github.com/ryanoasis/nerd-fonts/releases/latest/download/JetBrainsMono.tar.xz" "$TMP_ROOT/font.tar.xz" \
        && tar -xJf "$TMP_ROOT/font.tar.xz" -C "$font_dir"; then
        fc-cache -f "$font_dir"
    else
        log_warn "Could not install the Nerd Font"
    fi
}

if [ -z "${SKIP_FONT:-}" ]; then
    if [[ "$OS" == "Darwin" ]]; then
        if [[ "$PACKAGE_MANAGER" == "brew" ]]; then
            run brew install --cask font-jetbrains-mono-nerd-font || log_warn "Could not install the Nerd Font"
        else
            log_warn "Install a Nerd Font manually (e.g. JetBrainsMono Nerd Font) and select it in your terminal"
        fi
    elif grep -qi 'nerd font' <<< "$(fc-list 2>/dev/null || true)"; then
        log_info "Nerd Font already installed"
    elif command -v fc-cache >/dev/null 2>&1; then
        if [ -n "$DRY_RUN" ]; then
            log_info "[dry-run] would install the JetBrainsMono Nerd Font"
        else
            install_nerd_font
        fi
    else
        log_warn "fc-cache not available; install a Nerd Font manually"
    fi
fi

# --- 4. Zsh as the default shell (Linux only) ---
if [[ "$OS" != "Darwin" ]]; then
    ZSH_PATH="$(command -v zsh || true)"
    if [ -z "$ZSH_PATH" ]; then
        log_warn "zsh is not installed; the default shell is left unchanged"
    else
        CURRENT_LOGIN_SHELL="$(getent passwd "$(id -un)" | cut -d: -f7)"
        if [ "$CURRENT_LOGIN_SHELL" != "$ZSH_PATH" ]; then
            log_info "Changing the default shell to Zsh..."
            if ! grep -qx "$ZSH_PATH" /etc/shells; then
                if [ -n "$DRY_RUN" ]; then
                    log_info "[dry-run] would add $ZSH_PATH to /etc/shells"
                else
                    echo "$ZSH_PATH" | as_root tee -a /etc/shells >/dev/null
                fi
            fi
            run chsh -s "$ZSH_PATH" 2>/dev/null \
                || as_root usermod -s "$ZSH_PATH" "$(id -un)" \
                || log_warn "Could not change the shell; run: chsh -s $ZSH_PATH"
        fi
    fi
fi

# --- 5. Git with Delta ---
if [ -z "${SKIP_GIT_CONFIG:-}" ] && command -v delta >/dev/null 2>&1; then
    log_info "Configuring Git with Delta..."
    backup_file "$HOME/.gitconfig"
    run git config --global core.pager "delta"
    run git config --global interactive.diffFilter "delta --color-only"
    run git config --global delta.navigate true
    run git config --global delta.light false
    run git config --global delta.line-numbers true
    run git config --global delta.side-by-side false
    run git config --global merge.conflictStyle "zdiff3"
fi

# --- 6. Starship prompt (~/.config/starship.toml) ---
log_info "Configuring Starship prompt..."
run mkdir -p "$HOME/.config"
backup_file "$HOME/.config/starship.toml"
write_file "$HOME/.config/starship.toml" << 'EOF'
# ~/.config/starship.toml - optimized Starship prompt configuration
add_newline = true

format = """
$os\
$directory\
$git_branch\
$git_status\
$package\
$nodejs\
$python\
$rust\
$golang\
$docker_context\
$kubernetes\
$cmd_duration\
$line_break\
$character"""

[character]
success_symbol = "[❯](bold green)"
error_symbol = "[❯](bold red)"
vimcmd_symbol = "[❮](bold green)"

[directory]
style = "bold cyan"
truncation_length = 4
truncation_symbol = "…/"
read_only = " 󰌾"

[git_branch]
symbol = " "
style = "bold purple"
format = "[$symbol$branch]($style) "

[git_status]
style = "bold red"
format = "([\\[$all_status$ahead_behind\\]]($style) )"
ahead = "⇡${count}"
behind = "⇣${count}"
diverged = "⇕⇡${ahead_count}⇣${behind_count}"
conflicted = "󰞇 "
untracked = "?${count}"
modified = "!${count}"
staged = "+${count}"
renamed = "»${count}"
deleted = "✘${count}"

[cmd_duration]
min_time = 2_000
style = "bold yellow"
format = "took [$duration]($style) "

[nodejs]
symbol = "󰎙 "
style = "bold green"
format = "via [$symbol($version )]($style)"

[python]
symbol = "󰌠 "
style = "bold yellow"
format = "via [${symbol}${pyenv_prefix}(${version} )(\\($virtualenv\\) )]($style)"

[rust]
symbol = "󱘗 "
style = "bold red"
format = "via [$symbol($version )]($style)"

[golang]
symbol = "󰟓 "
style = "bold cyan"
format = "via [$symbol($version )]($style)"

[docker_context]
symbol = "󰡨 "
style = "blue bold"
format = "at [$symbol$context]($style) "

[package]
symbol = "󰏗 "
style = "bold 240"
format = "is [$symbol$version]($style) "

[kubernetes]
disabled = false
symbol = "󱃾 "
format = "[$symbol$context( \\($namespace\\))]($style) "
style = "bold blue"

[[kubernetes.contexts]]
context_pattern = ".*prod.*"
style = "bold red"

[[kubernetes.contexts]]
context_pattern = ".*stg.*"
style = "bold yellow"

[[kubernetes.contexts]]
context_pattern = ".*dev.*"
style = "bold green"
EOF

# --- 7. Yazi (~/.config/yazi/yazi.toml) ---
log_info "Configuring Yazi..."
run mkdir -p "$HOME/.config/yazi"
backup_file "$HOME/.config/yazi/yazi.toml"
write_file "$HOME/.config/yazi/yazi.toml" << 'EOF'
# ~/.config/yazi/yazi.toml - optimized Yazi configuration

[mgr]
show_hidden = false
show_symlink = true
scrolloff = 5

[preview]
wrap = "yes"
tab_size = 2
max_width = 1200
max_height = 1200
image_filter = "lanczos3"
image_quality = 90

[opener]
edit = [
    { run = '${EDITOR:-nano} "$@"', block = true, for = "unix" },
]
open = [
    { run = 'open "$@"', desc = "Open with default app", for = "macos" },
    { run = 'xdg-open "$@"', desc = "Open with default app", for = "linux" },
]
EOF

# --- 8. Universal ~/.zshrc ---
log_info "Configuring ~/.zshrc..."
backup_file "$HOME/.zshrc"
write_file "$HOME/.zshrc" << 'EOF'
# ~/.zshrc: modern cross-platform zsh configuration

# --- Base environment and PATH ---
if [ -f "$HOME/.local/bin/env" ]; then
    . "$HOME/.local/bin/env"
fi

typeset -U path PATH
for dir in /opt/zerobrew/sbin /opt/zerobrew/bin /opt/homebrew/sbin /opt/homebrew/bin "$HOME/.local/bin"; do
    if [[ -d "$dir" ]]; then
        path=("$dir" $path)
    fi
done
unset dir

if [[ -d "$HOME/.lmstudio/bin" ]]; then
    path+=("$HOME/.lmstudio/bin")
fi

# kubectl plugins installed with krew
if [[ -d "${KREW_ROOT:-$HOME/.krew}/bin" ]]; then
    path+=("${KREW_ROOT:-$HOME/.krew}/bin")
fi

# --- Shared and persistent history ---
HISTFILE="$HOME/.zsh_history"
HISTSIZE=50000
SAVEHIST=50000
setopt EXTENDED_HISTORY
setopt SHARE_HISTORY
setopt HIST_IGNORE_ALL_DUPS
setopt HIST_IGNORE_SPACE
setopt HIST_REDUCE_BLANKS

# --- Shell behavior and editor ---
setopt AUTO_CD
export EDITOR="${EDITOR:-nano}"
export VISUAL="${VISUAL:-$EDITOR}"

# --- Native completion system and package functions ---
for dir in /opt/zerobrew/share/zsh/site-functions /opt/homebrew/share/zsh/site-functions /usr/local/share/zsh/site-functions; do
    if [[ -d "$dir" ]]; then
        fpath=("$dir" $fpath)
    fi
done
unset dir

autoload -Uz compinit
# Rebuild the completion dump at most once a day; otherwise trust the cached one
# (delete ~/.zcompdump to pick up new completions immediately)
_zcomp_stale=( "$HOME/.zcompdump"(N.mh+24) )
if (( $#_zcomp_stale )) || [[ ! -f "$HOME/.zcompdump" ]]; then
    compinit -d "$HOME/.zcompdump"
else
    compinit -C -d "$HOME/.zcompdump"
fi
unset _zcomp_stale

# Sources the output of a slow init command from a cache that is rebuilt only when
# the binary changes. Usage: _cached_init <cache-name> <command> [args...]
_cached_init() {
    local name="$1" bin cache
    shift
    bin="${commands[$1]}"
    [[ -n "$bin" ]] || return 1
    cache="${XDG_CACHE_HOME:-$HOME/.cache}/zsh/$name.zsh"
    if [[ ! -s "$cache" || "$bin" -nt "$cache" ]]; then
        mkdir -p "${cache:h}"
        "$@" >| "$cache" 2>/dev/null || { rm -f "$cache"; return 1; }
    fi
    source "$cache"
    return 0
}
zstyle ':completion:*' menu select
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}'
zstyle ':completion:*' list-colors "${(s.:.)LS_COLORS}"

# --- FZF search engine (integrated with fd, bat and eza) ---
if command -v fd >/dev/null 2>&1; then
    export FZF_DEFAULT_COMMAND='fd --type f --strip-cwd-prefix --hidden --follow --exclude .git'
    export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND"
    export FZF_ALT_C_COMMAND='fd --type d --strip-cwd-prefix --hidden --follow --exclude .git'
fi

# Alt-P toggles the preview (Ctrl-/ needs Shift+7 on an ISO Spanish keyboard)
export FZF_DEFAULT_OPTS="--height 45% --layout=reverse --border --inline-info --bind=alt-p:toggle-preview"
export FZF_CTRL_T_OPTS="--preview 'if [ -d {} ]; then eza --tree --color=always --icons=always {} | head -200; else bat --color=always --line-range :300 {}; fi'"
export FZF_ALT_C_OPTS="--preview 'eza --tree --color=always --icons=always {} | head -200'"

# fzf key bindings and fuzzy completion (`fzf --zsh` needs fzf >= 0.48); loaded
# before fzf-tab because it binds Tab to fzf-completion
if command -v fzf >/dev/null 2>&1; then
    if _cached_init fzf fzf --zsh; then
        :
    else
        for f in /usr/share/doc/fzf/examples/key-bindings.zsh /usr/share/doc/fzf/examples/completion.zsh; do
            [[ -f "$f" ]] && source "$f"
        done
        unset f
    fi
fi

# fzf-tab: interactive completion menu with previews (must load after compinit
# and before autosuggestions / syntax highlighting)
FZF_TAB_PATHS=(
    "$HOME/.fzf-tab/fzf-tab.plugin.zsh"
    "/opt/homebrew/opt/fzf-tab/share/fzf-tab/fzf-tab.zsh"
    "/opt/zerobrew/share/fzf-tab/fzf-tab.zsh"
    "/usr/share/fzf-tab/fzf-tab.zsh"
)

for ftp in "${FZF_TAB_PATHS[@]}"; do
    if [[ -f "$ftp" ]]; then
        source "$ftp"
        zstyle ':fzf-tab:*' switch-group '<' '>'
        zstyle ':fzf-tab:*' fzf-bindings 'alt-p:toggle-preview'
        zstyle ':fzf-tab:complete:(cd|z|pushd):*' fzf-preview 'eza -1 --color=always --icons=always $realpath 2>/dev/null || ls -1 $realpath'
        zstyle ':fzf-tab:complete:*:*' fzf-preview '
            if [ -d "$realpath" ]; then
                eza -1 --color=always --icons=always "$realpath" 2>/dev/null || ls -1 "$realpath"
            elif [ -f "$realpath" ]; then
                bat --color=always --line-range :200 "$realpath" 2>/dev/null || cat "$realpath"
            fi'
        zstyle ':fzf-tab:complete:(kill|ps):argument-rest' fzf-preview '
            [[ $group == "[process ID]" ]] && ps -p $word -o pid,user,%cpu,%mem,command 2>/dev/null'
        zstyle ':fzf-tab:complete:(kill|ps):argument-rest' fzf-flags '--preview-window=down:3:wrap'
        zstyle ':fzf-tab:complete:git-(checkout|switch):*' fzf-preview 'git log --oneline --graph --color=always -n 10 $word 2>/dev/null'
        break
    fi
done
unset ftp

# --- Starship prompt (with native fallback) ---
if command -v starship >/dev/null 2>&1 && _cached_init starship starship init zsh --print-full-init; then
    :
else
    autoload -Uz vcs_info
    precmd() { vcs_info }
    zstyle ':vcs_info:git:*' formats ' (%F{yellow}%b%f)'
    setopt PROMPT_SUBST
    PROMPT='%F{green}%n@%m%f:%F{blue}%~%f${vcs_info_msg_0_}%# '
fi

# --- Prefix history search (up / down arrows) ---
autoload -Uz up-line-or-beginning-search down-line-or-beginning-search
zle -N up-line-or-beginning-search
zle -N down-line-or-beginning-search
bindkey '^[[A' up-line-or-beginning-search
bindkey '^[[B' down-line-or-beginning-search
bindkey '^[[H' beginning-of-line
bindkey '^[[F' end-of-line
bindkey '^[[3~' delete-char
# Home / End / Delete variants sent by different terminals
bindkey '^[[1~' beginning-of-line
bindkey '^[[4~' end-of-line
bindkey '^[OH' beginning-of-line
bindkey '^[OF' end-of-line
# Word movement and deletion with Ctrl / Alt + arrows and Ctrl + Delete
bindkey '^[[1;5D' backward-word        # Ctrl + Left arrow
bindkey '^[[1;5C' forward-word         # Ctrl + Right arrow
bindkey '^[[1;3D' backward-word        # Alt + Left arrow
bindkey '^[[1;3C' forward-word         # Alt + Right arrow
bindkey '^[[3;5~' kill-word            # Ctrl + Delete

# --- Zoxide (fast directory jumping with 'z') ---
if command -v zoxide >/dev/null 2>&1; then
    _cached_init zoxide zoxide init zsh
fi

# --- Modern replacements and aliases ---
if command -v eza >/dev/null 2>&1; then
    alias ls='eza --icons=always'
    alias ll='eza -la --icons=always --git'
    alias la='eza -a --icons=always'
    alias l='eza -l --icons=always'
    alias tree='eza --tree --icons=always'
else
    if [[ "$OSTYPE" == "darwin"* ]]; then
        alias ls='ls -G'
    else
        alias ls='ls --color=auto'
    fi
    alias ll='ls -alF'
    alias la='ls -A'
    alias l='ls -CF'
fi

if command -v bat >/dev/null 2>&1; then
    alias cat='bat --paging=never'
elif command -v batcat >/dev/null 2>&1; then
    alias cat='batcat --paging=never'
    alias bat='batcat'
fi

alias grep='grep --color=auto'

if command -v duf >/dev/null 2>&1; then
    alias df='duf'
fi

if command -v btop >/dev/null 2>&1; then
    alias top='btop'
fi

if command -v lazygit >/dev/null 2>&1; then
    alias lg='lazygit'
fi

if command -v delta >/dev/null 2>&1; then
    alias d='delta'
fi

if command -v fastfetch >/dev/null 2>&1; then
    alias ff='fastfetch'
fi

if command -v zellij >/dev/null 2>&1; then
    alias zj='zellij'
    alias zr='zellij run --'
fi

if command -v lazydocker >/dev/null 2>&1; then
    alias lzd='lazydocker'
fi

# Per-directory environment variables from .envrc (run `direnv allow` to trust one)
if command -v direnv >/dev/null 2>&1; then
    _cached_init direnv direnv hook zsh
fi

if command -v kubectl >/dev/null 2>&1; then
    alias k='kubectl'
    alias kg='kubectl get'
    alias kgp='kubectl get pods'
    alias kgpa='kubectl get pods -A'
    alias kgn='kubectl get nodes'
    alias kgs='kubectl get svc'
    alias kgd='kubectl get deploy'
    alias kd='kubectl describe'
    alias kl='kubectl logs'
    alias klf='kubectl logs -f'
    alias kex='kubectl exec -it'
    alias kaf='kubectl apply -f'
    alias kdf='kubectl delete -f'
    alias kgi='kubectl get ingress'
    alias kgns='kubectl get namespaces'
    alias kpf='kubectl port-forward'
    alias kctx='kubectl config current-context'
    _cached_init kubectl kubectl completion zsh
    compdef k=kubectl kg=kubectl kgp=kubectl kgpa=kubectl kgn=kubectl kgs=kubectl kgd=kubectl \
        kgi=kubectl kgns=kubectl kpf=kubectl kd=kubectl kl=kubectl klf=kubectl kex=kubectl \
        kaf=kubectl kdf=kubectl

    # kns [namespace]: show or set the namespace of the current kubectl context
    kns() {
        if [[ -z "$1" ]]; then
            command kubectl config view --minify --output 'jsonpath={..namespace}'
            echo
        else
            command kubectl config set-context --current --namespace "$1"
        fi
    }
    _kns() {
        compadd -- ${(f)"$(command kubectl get namespaces -o name 2>/dev/null | sed 's|^namespace/||')"}
    }
    compdef _kns kns

    # Colorized output; the aliases above expand through it
    if command -v kubecolor >/dev/null 2>&1; then
        alias kubectl='kubecolor'
    fi
fi

if command -v k9s >/dev/null 2>&1; then
    _cached_init k9s k9s completion zsh
fi

if command -v stern >/dev/null 2>&1; then
    alias ks='stern'
    _cached_init stern stern --completion zsh
    compdef ks=stern
fi

if command -v helm >/dev/null 2>&1; then
    alias h='helm'
    _cached_init helm helm completion zsh
    compdef h=helm
fi

if command -v kubeconform >/dev/null 2>&1; then
    alias kconf='kubeconform -summary'
fi

if command -v argocd >/dev/null 2>&1; then
    _cached_init argocd argocd completion zsh
fi

if command -v kustomize >/dev/null 2>&1; then
    _cached_init kustomize kustomize completion zsh
fi

if command -v kubectx >/dev/null 2>&1; then
    alias kx='kubectx'
    if [[ -z ${_comps[kubectx]} && -r /opt/kubectx/completion/_kubectx.zsh ]]; then
        eval "_kubectx() { $(</opt/kubectx/completion/_kubectx.zsh) }"
        compdef _kubectx kubectx kx
    fi
fi

if command -v kubens >/dev/null 2>&1; then
    alias kn='kubens'
    if [[ -z ${_comps[kubens]} && -r /opt/kubectx/completion/_kubens.zsh ]]; then
        eval "_kubens() { $(</opt/kubectx/completion/_kubens.zsh) }"
        compdef _kubens kubens kn
    fi
fi

if [ -f "$HOME/.bash_aliases" ]; then
    source "$HOME/.bash_aliases"
fi

# --- Fish-like autosuggestions ---
AUTOSUGGEST_PATHS=(
    "/opt/zerobrew/share/zsh-autosuggestions/zsh-autosuggestions.zsh"
    "/opt/zerobrew/prefix/share/zsh-autosuggestions/zsh-autosuggestions.zsh"
    "/opt/homebrew/share/zsh-autosuggestions/zsh-autosuggestions.zsh"
    "/usr/local/share/zsh-autosuggestions/zsh-autosuggestions.zsh"
    "/usr/share/zsh-autosuggestions/zsh-autosuggestions.zsh"
    "/usr/share/zsh/plugins/zsh-autosuggestions/zsh-autosuggestions.zsh"
)

for p in "${AUTOSUGGEST_PATHS[@]}"; do
    if [[ -f "$p" ]]; then
        ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE='fg=244'
        ZSH_AUTOSUGGEST_STRATEGY=(history completion)
        source "$p"

        # Ergonomic bindings (no need to reach for the arrow keys)
        bindkey '^ ' autosuggest-accept        # Ctrl + Space
        bindkey '^@' autosuggest-accept        # Ctrl + Space (variant)
        bindkey '^F' autosuggest-accept        # Ctrl + F
        bindkey '^E' autosuggest-accept        # Ctrl + E (end of line)
        bindkey '^[f' forward-word             # Alt + F (word by word)
        bindkey '^[[C' forward-char            # Right arrow
        bindkey '^[OC' forward-char            # Right arrow
        bindkey '^[[1;5C' forward-word         # Ctrl + Right arrow

        # Smart Tab: accept the suggestion if there is one, otherwise complete
        # (through fzf-tab when it is loaded)
        smart-tab() {
            if [[ -n "$POSTDISPLAY" ]]; then
                zle autosuggest-accept
            elif (( $+widgets[fzf-tab-complete] )); then
                zle fzf-tab-complete
            else
                zle expand-or-complete
            fi
        }
        zle -N smart-tab
        bindkey '^I' smart-tab
        break
    fi
done
unset p

# --- Syntax highlighting (must be sourced last among the plugins) ---
SYNTAX_PATHS=(
    "/opt/zerobrew/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh"
    "/opt/zerobrew/prefix/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh"
    "/opt/homebrew/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh"
    "/usr/local/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh"
    "/usr/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh"
    "/usr/share/zsh/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh"
)

for p in "${SYNTAX_PATHS[@]}"; do
    if [[ -f "$p" ]]; then
        source "$p"
        break
    fi
done
unset p

# --- Yazi wrapper: change directory on exit ---
function y() {
    local tmp="$(mktemp -t "yazi-cwd.XXXXXX")" cwd
    yazi "$@" --cwd-file="$tmp"
    if cwd="$(command cat -- "$tmp")" && [ -n "$cwd" ] && [ "$cwd" != "$PWD" ]; then
        builtin cd -- "$cwd"
    fi
    rm -f -- "$tmp"
}

# --- Machine-local additions (not managed by this installer) ---
if [[ -f "$HOME/.zshrc.local" ]]; then
    source "$HOME/.zshrc.local"
fi
EOF

if command -v tldr >/dev/null 2>&1; then
    run tldr --update || log_warn "Could not download the tldr pages (run: tldr --update)"
fi

log_success "Installation completed successfully!"
echo -e "${GREEN}To start using your new environment, run:${NC}"
echo -e "    ${YELLOW}exec zsh${NC}"
echo -e "${YELLOW}Remember to select a Nerd Font (e.g. JetBrainsMono Nerd Font) in your terminal profile.${NC}"
