# --- 1. System Erkennung & Bootstrap Logik ---

# Funktion zur Erkennung des OS
get_os_info() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS_ID=$ID
        OS_LIKE=$ID_LIKE
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        OS_ID="macos"
    elif [[ "$OSTYPE" == "freebsd"* ]]; then
        OS_ID="freebsd"
    elif [ -d "/data/data/com.termux" ]; then
        OS_ID="termux"
    fi
}
get_os_info

# Automatisches Setup der Config-Dateien (Fastfetch & Neovim)
setup_configs() {
    # Fastfetch Config erstellen
    if [ ! -f ~/.config/fastfetch/fastfetch.jsonc ]; then
        echo "--> Erstelle Fastfetch Config..."
        mkdir -p ~/.config/fastfetch
        cat <<EOF > ~/.config/fastfetch/fastfetch.jsonc
{
    "\$schema": "https://github.com/fastfetch-cli/fastfetch/raw/dev/doc/json_schema.json",
    "logo": { "type": "small", "position": "top", "padding": { "top": 1, "bottom": 0 } },
    "display": { "separator": " -> ", "color": { "separator": "1" }, "key": { "type": "both", "paddingLeft": 0 } },
    "modules": [
        { "type": "custom", "format": "┌──────── {#1}System Information{#} ────────┐" },
        { "type": "os", "key": " OS     ", "keyColor": "red" },
        { "type": "host", "key": " Machine", "keyColor": "green" },
        { "type": "kernel", "key": " Kernel ", "keyColor": "magenta" },
        { "type": "uptime", "key": " Uptime ", "keyColor": "red" },
        { "type": "shell", "key": " Shell  ", "keyColor": "cyan" },
        { "type": "cpu", "key": " CPU    ", "keyColor": "yellow" },
        { "type": "memory", "key": " Memory ", "keyColor": "magenta" },
        { "type": "swap", "key": " Swap   ", "keyColor": "magenta" },
        { "type": "custom", "format": "└──────────────────────────────────────┘" }
    ]
}
EOF
    fi

# Neovim Config erstellen
    if [ ! -f ~/.config/nvim/init.lua ]; then
        echo "--> Erstelle Neovim Config..."
        mkdir -p ~/.config/nvim
        cat <<EOF > ~/.config/nvim/init.lua
-- True Color Support erzwingen
vim.opt.termguicolors = true

-- Maus deaktivieren
vim.opt.mouse = ""

-- Einrückung: 4 Leerzeichen
vim.opt.shiftwidth = 4
vim.opt.tabstop = 4
vim.opt.expandtab = true

-- Transparenz erzwingen (Normaler Text & UI-Elemente)
vim.cmd[[highlight Normal guibg=NONE ctermbg=NONE]]
vim.cmd[[highlight NonText guibg=NONE ctermbg=NONE]]
vim.cmd[[highlight SignColumn guibg=NONE ctermbg=NONE]]
vim.cmd[[highlight EndOfBuffer guibg=NONE ctermbg=NONE]]

-- Zeilennummern & Cursorline
vim.opt.number = true
vim.opt.relativenumber = false
vim.opt.cursorline = true

-- FARBEN & HINTERGRÜNDE (Kein Grau mehr)
-- LineNr: Inaktive Nummern (Hellgrau, Hintergrund transparent)
vim.api.nvim_set_hl(0, 'LineNr', { fg = '#a0a0a0', bg = 'NONE' })

-- CursorLineNr: Aktuelle Zeilennummer (Neon-Gelb, Hintergrund transparent)
vim.api.nvim_set_hl(0, 'CursorLineNr', { fg = '#ffcc00', bg = 'NONE', bold = true })

-- CursorLine: Der Balken der aktiven Zeile (Hintergrund komplett weg)
vim.api.nvim_set_hl(0, 'CursorLine', { bg = 'NONE', ctermbg = 'NONE' })
EOF
    fi
}

install_missing_packages() {
    echo "--> Komponenten fehlen. Starte Bootstrap für $OS_ID..."
    local pkgs=(git neovim fastfetch eza zsh curl)
    local s=""; (( $+commands[sudo] )) && s="sudo"

    case "$OS_ID" in
        arch|cachyos)
            $s pacman -Syu --needed --noconfirm "${pkgs[@]}" shadow
            ;;
        alpine)
            $s apk add "${pkgs[@]}" ncurses-terminfo-base shadow
            ;;
        debian|ubuntu|kali)
            $s apt update
            # In Debian heißt das Paket 'passwd' oder einfach nur 'shadow' (falls nötig)
            $s apt install -y git neovim fastfetch eza zsh curl
            ;;
        fedora|rhel)
            $s dnf install -y "${pkgs[@]}" shadow-utils
            ;;
        termux)
            pkg install -y git neovim fastfetch eza zsh curl
            ;;
        freebsd)
            $s pkg install -y git neovim fastfetch eza zsh curl
            ;;
    esac
    setup_configs
}

# Bootstrap Trigger: Wenn eza oder fastfetch fehlen
if ! command -v fastfetch &> /dev/null || ! command -v eza &> /dev/null; then
    install_missing_packages
fi

# --- 2. ZSH Plugins & Theme (Zinit) ---

(( $+commands[fastfetch] )) && sleep 0.1 && fastfetch --config ~/.config/fastfetch/fastfetch.jsonc

if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then
  source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh"
fi

ZINIT_HOME="${XDG_DATA_HOME:-${HOME}/.local/share}/zinit/zinit.git"
[ ! -d "$ZINIT_HOME" ] && mkdir -p "$(dirname $ZINIT_HOME)" && git clone https://github.com/zdharma-continuum/zinit.git "$ZINIT_HOME"
source "${ZINIT_HOME}/zinit.zsh"

zinit ice depth=1; zinit light romkatv/powerlevel10k
zinit light zsh-users/zsh-syntax-highlighting
zinit light zsh-users/zsh-completions
zinit light zsh-users/zsh-autosuggestions
zinit snippet OMZ::plugins/git/git.plugin.zsh
zinit load 'zsh-users/zsh-history-substring-search'

autoload -Uz compinit && compinit
zinit cdreplay -q
[[ ! -f ~/.p10k.zsh ]] || source ~/.p10k.zsh

# --- 3. Aliases & Keybindings ---

alias c='clear'
alias x='exit'
alias l='eza -lagh --icons --group-directories-first'
alias yay='yay --noconfirm'
alias yayold='yay'

# Keybindings
bindkey -e
bindkey "^[[1;5C" forward-word
bindkey "^[[1;5D" backward-word
bindkey "^[[3~" delete-char
bindkey '^[[A' history-substring-search-up
bindkey '^[[B' history-substring-search-down

# --- 4. Das Ultimative Update Script ---

update_system() {
    # Hilfsfunktion für Flatpak (nur ausführen wenn installiert)
    update_flatpak() {
        if (( $+commands[flatpak] )); then
            echo "--- Flatpak Update ---"
            flatpak update -y && flatpak uninstall --unused -y
        fi
    }

    local s=""; (( $+commands[sudo] )) && s="sudo"

    case "$OS_ID" in
        arch|cachyos)
            echo "--- Arch/CachyOS erkannt ---"
            if (( $+commands[yay] )); then
                yay -Syu --needed --noconfirm
            else
                $s pacman -Syu --noconfirm
            fi
            update_flatpak

            # Verwaiste Pakete entfernen
            local orphans=$(pacman -Qdtq)
            if [[ -n "$orphans" ]]; then
                echo "--- Entferne verwaiste Pakete ---"
                $s pacman -Rns ${=orphans} --noconfirm
            else
                echo "--- System ist bereits sauber ---"
            fi
            ;;

        alpine)
            echo "--- Alpine Linux erkannt ---"
            $s apk update && $s apk upgrade && update_flatpak
            ;;

        debian|ubuntu|kali)
            echo "--- Debian/Ubuntu erkannt ---"
            $s apt update && $s apt upgrade -y && update_flatpak
            $s apt autoremove -y
            ;;

        fedora)
            echo "--- Fedora erkannt ---"
            $s dnf upgrade --refresh -y && update_flatpak
            $s dnf autoremove -y
            ;;

        termux)
            echo "--- Termux erkannt ---"
            pkg upgrade -y && update_flatpak
            ;;

        freebsd)
            echo "--- FreeBSD erkannt ---"
            $s pkg update && $s pkg upgrade -y && update_flatpak
            ;;

        *)
            # Fallback für Derivate
            if [[ "$OS_LIKE" == *"arch"* ]]; then
                $s pacman -Syu --noconfirm && update_flatpak
            elif [[ "$OS_LIKE" == *"debian"* ]]; then
                $s apt update && $s apt upgrade -y && update_flatpak
            else
                echo "Unbekanntes System: $OS_ID. Update bitte manuell."
            fi
            ;;
    esac
}
alias u='update_system'

# Environment
export EDITOR='nvim'
export VISUAL='nvim'
WORDCHARS='*?_-.[]~=&;!#$%^(){}<>'