#!/usr/bin/env bash
set -euo pipefail

echo "=== INXS ZSH Full Installer V3 — With ket-bash_aliases ==="

USER_HOME="$HOME"
ZSH_BIN="/usr/bin/zsh"
ZSH_DIR="$USER_HOME/.oh-my-zsh"
ZSH_CUSTOM="$ZSH_DIR/custom"

###############################################################################
# 0) Show current shell
###############################################################################
echo "[i] Current shell: $0"

###############################################################################
# 1) FULL RESET
###############################################################################
echo "[+] Resetting old configs..."
rm -rf "$ZSH_DIR" || true
rm -f  "$USER_HOME/.zshrc" "$USER_HOME/.zshrc.pre-oh-my-zsh" \
       "$USER_HOME/.p10k.zsh" "$USER_HOME/.shell_common"
rm -rf "$USER_HOME/.fzf" "$USER_HOME/.fzf.zsh"

echo "[+] Removing Debian fzf (if any)..."
sudo apt remove --purge -y fzf || true

###############################################################################
# 2) Install dependencies
###############################################################################
echo "[+] Installing zsh, git, curl..."
sudo apt update -y
sudo apt install -y zsh git curl

if ! command -v zsh >/dev/null; then
  echo "[ERR] Zsh installation failed."
  exit 1
fi

echo "[+] Zsh located at: $(command -v zsh)"

###############################################################################
# 3) Set zsh as default shell
###############################################################################
echo "[+] Setting Zsh as default for user..."
chsh -s "$ZSH_BIN" "$USER" || true

# Initialize zsh environment once
zsh -c 'echo "[i] Inside zsh bootstrap: $0"'

###############################################################################
# 4) Install Oh-My-Zsh
###############################################################################
echo "[+] Installing Oh-My-Zsh..."
export RUNZSH=no
export CHSH=no
sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"

if [[ ! -d "$ZSH_DIR" ]]; then
  echo "[ERR] Installation of Oh-My-Zsh failed."
  exit 1
fi

###############################################################################
# 5) Install Powerlevel10k theme
###############################################################################
echo "[+] Installing Powerlevel10k theme..."
git clone --depth=1 https://github.com/romkatv/powerlevel10k.git \
  "$ZSH_CUSTOM/themes/powerlevel10k"

###############################################################################
# 6) Install FZF (GitHub)
###############################################################################
echo "[+] Installing fzf (GitHub version)..."
git clone --depth 1 https://github.com/junegunn/fzf.git "$USER_HOME/.fzf"
"$USER_HOME/.fzf/install" --key-bindings --completion --no-bash --no-fish --no-update-rc

###############################################################################
# 7) Install Zsh plugins
###############################################################################
echo "[+] Installing Zsh plugins..."
mkdir -p "$ZSH_CUSTOM/plugins"

git clone --depth=1 https://github.com/zsh-users/zsh-autosuggestions \
  "$ZSH_CUSTOM/plugins/zsh-autosuggestions"

git clone --depth=1 https://github.com/zsh-users/zsh-syntax-highlighting \
  "$ZSH_CUSTOM/plugins/zsh-syntax-highlighting"

git clone --depth=1 https://github.com/zsh-users/zsh-history-substring-search \
  "$ZSH_CUSTOM/plugins/zsh-history-substring-search"

git clone --depth=1 https://github.com/Aloxaf/fzf-tab \
  "$ZSH_CUSTOM/plugins/fzf-tab"


###############################################################################
# 8) Install ket-bash_aliases only if missing
###############################################################################
echo "[+] Checking ket-bash_aliases..."

KET_DIR="$HOME/ket-bash_aliases"
GITEA_SCRIPT="/opt/scripts_remote/git/gitea_setup.sh"

if [[ -d "$KET_DIR" ]]; then
    echo "[+] ket-bash_aliases already present — skipping clone."
else
    echo "[+] ket-bash_aliases not found — cloning from Gitea..."

    if [[ ! -x "$GITEA_SCRIPT" ]]; then
        echo "[!] ERROR: cannot clone repository — $GITEA_SCRIPT missing or not executable."
    else
        # Must run from $HOME
        pushd "$HOME" >/dev/null || true

        "$GITEA_SCRIPT" --clone --repo-name ket-bash_aliases || \
            echo "[!] WARNING: gitea_setup.sh failed (continuing)"

        popd >/dev/null || true
    fi
fi

# Vérification finale
if [[ -d "$KET_DIR" ]]; then
    echo "[+] ket-bash_aliases installed."
else
    echo "[!] ket-bash_aliases NOT installed."
fi


###############################################################################
# 9) Create ~/.shell_common (INXS shared config incl. ket-bash_aliases)
###############################################################################
echo "[+] Creating ~/.shell_common..."

cat > "$USER_HOME/.shell_common" <<'EOF'
# ============================================================
# INXS Shared Shell Configuration (Bash & Zsh)
# ============================================================

# Load INXS alias pack
if [ -f "$HOME/ket-bash_aliases/.bash_aliases" ]; then
    source "$HOME/ket-bash_aliases/.bash_aliases"
fi
EOF

###############################################################################
# 10) Create a clean and optimized ~/.zshrc
###############################################################################
echo "[+] Generating ~/.zshrc..."

cat > "$USER_HOME/.zshrc" <<'EOF'
# ============================================================
#  INXS – ZSH CONFIGURATION (Stable, Optimized, No Conflicts)
# ============================================================

export ZSH="$HOME/.oh-my-zsh"
export PATH="$HOME/.fzf/bin:$PATH"

# Theme
ZSH_THEME="powerlevel10k/powerlevel10k"

# Plugins
plugins=(
  git
  fzf-tab
  zsh-autosuggestions
  zsh-syntax-highlighting
  zsh-history-substring-search
)

# Oh-My-Zsh core
source $ZSH/oh-my-zsh.sh

# Shared INXS configuration
[ -f ~/.shell_common ] && source ~/.shell_common

# fzf integration
[ -f ~/.fzf.zsh ] && source ~/.fzf.zsh

# Syntax highlighting (must be last)
source $ZSH/custom/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh

# ============================================================
#  KEYBINDINGS – CORRECT FOR YOUR TERMINAL (^[[A B C D)
# ============================================================

bindkey -e  # enforce emacs mode

# history substring search
bindkey '^[[A' history-substring-search-up
bindkey '^[[B' history-substring-search-down

# Accept autosuggestion with right arrow
bindkey '^[[C' autosuggest-accept

# normal left/right
bindkey '^[[D' backward-char
bindkey '^[[C' forward-char

# ============================================================
#  FZF-TAB
# ============================================================
zstyle ':completion:*' menu no
zstyle ':fzf-tab:*' switch-group '<' '>'
zstyle ':fzf-tab:*' fzf-preview 'bat --style=numbers --color=always {}'

# ============================================================
#  HISTORY
# ============================================================
HISTFILE=~/.zsh_history
HISTSIZE=50000
SAVEHIST=50000
setopt share_history
setopt hist_ignore_all_dups

# ============================================================
#  ITERM2 REMOTE SHELL INTEGRATION (Zsh version, lightweight)
# ============================================================
# Works when SSH'ing from iTerm2. Updates tab title & sends dir/hostname.
# No heavy integration, no PROMPT_COMMAND hacks.

if [[ -n "$SSH_CONNECTION" ]]; then
  iterm2_osc() {
    printf "\033]%s\007" "$1"
  }

  function iterm2_set_title() {
    local HOST_SHORT="${HOST%%.*}"
    iterm2_osc "0;${HOST_SHORT}"
  }

  function iterm2_send_state() {
    local HOST_SHORT="${HOST%%.*}"
    iterm2_osc "1337;RemoteHost=$USER@$HOST_SHORT"
    iterm2_osc "1337;CurrentDir=$PWD"
  }

  precmd_functions+=(iterm2_set_title)
  precmd_functions+=(iterm2_send_state)
fi

# ============================================================
#  POWERLEVEL10K CONFIG
# ============================================================
[[ -f ~/.p10k.zsh ]] && source ~/.p10k.zsh

EOF

###############################################################################
# 11) Create Powerlevel10k configuration (avoid wizard)
###############################################################################
echo "[+] Installing default INXS Powerlevel10k config..."

cat > "$USER_HOME/.p10k.zsh" <<'EOF'
# ===========================
# Powerlevel10k - INXS BLUE THEME (No Wizard)
# ===========================

# ===========================
# Powerlevel10k - INXS BLUE MINIMAL (Host + Dir only)
# ===========================

# INXS Colors
INXS_BLUE="#0050A4"
INXS_BRIGHT_BLUE="#008CFF"
INXS_WHITE="#FFFFFF"

# Prompt structure: only host and directory
typeset -g POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=(
  host                  # machine name
  dir                   # current directory
)

# Nothing on the right side
typeset -g POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=()

# Newline between prompts
typeset -g POWERLEVEL9K_PROMPT_ADD_NEWLINE=true

# Minimal separator
typeset -g POWERLEVEL9K_MULTILINE_LAST_PROMPT_PREFIX="%F{$INXS_BLUE}❯%f "

# Host style
typeset -g POWERLEVEL9K_HOST_BACKGROUND=$INXS_BLUE
typeset -g POWERLEVEL9K_HOST_FOREGROUND=$INXS_WHITE

# Directory style
typeset -g POWERLEVEL9K_DIR_BACKGROUND=$INXS_BRIGHT_BLUE
typeset -g POWERLEVEL9K_DIR_FOREGROUND=$INXS_WHITE
typeset -g POWERLEVEL9K_DIR_MAX_LENGTH=60
typeset -g POWERLEVEL9K_DIR_TRUNCATE_BEFORE_MARKER=true

# Remove icons (clean look)
typeset -g POWERLEVEL9K_ICON_PADDING=0
typeset -g POWERLEVEL9K_HIDE_BRANCH_ICON=true
typeset -g POWERLEVEL9K_HIDE_LOCK_SYMBOL=true
typeset -g POWERLEVEL9K_VISUAL_IDENTIFIER_EXPANSION=''

# Pure text, no fancy glyphs needed
POWERLEVEL9K_MODE='nerdfont-complete'
EOF

###############################################################################
echo "=== INXS ZSH Full Installation V3 — COMPLETED ==="
echo "➡ Run: exec zsh"
