#!/bin/bash

if [[ -z "${WELCOME_SCRIPT_PATH}" ]]; then
  WELCOME_SCRIPT_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." &>/dev/null && pwd)"
fi

. "${WELCOME_SCRIPT_PATH}/config/config_colors.sh"
. "${WELCOME_SCRIPT_PATH}/config/config_install.sh"
. "${WELCOME_SCRIPT_PATH}/func/common.sh"
. "${WELCOME_SCRIPT_PATH}/func/message.sh"
. "${WELCOME_SCRIPT_PATH}/func/network.sh"
. "${WELCOME_SCRIPT_PATH}/func/deb_sys.sh"

export SUDO=""
[[ "$EUID" -ne 0 ]] && command -v sudo >/dev/null 2>&1 && export SUDO="sudo"

# shellcheck disable=SC2034
RSA_KEY_FILE="$HOME/.ssh/id_rsa"

# Vérification JQ (une seule fois)
if ! command -v jq >/dev/null 2>&1; then
    echo -e "${COLOR_YELLOW}⚡ JQ manquant... installation...${NONE}"
    $SUDO apt-get update -qq && $SUDO apt-get install -y jq -qq
fi

# ==========================================
# 2. DÉFINITION DES DONNÉES (JSON)
# ==========================================
# OPTIMISATION : On parse le JSON en tableaux Bash UNE SEULE FOIS
mapfile -t ALL_DEB_INSTALL_IDS < <(echo "$CONFIG_DEB_INSTALL_JSON" | jq -r '.[].id')
mapfile -t ALL_DEB_INSTALL_LABELS < <(echo "$CONFIG_DEB_INSTALL_JSON" | jq -r '.[].label')
mapfile -t ALL_DEB_INSTALL_TYPES < <(echo "$CONFIG_DEB_INSTALL_JSON" | jq -r '.[].type')
mapfile -t ALL_DEB_INSTALL_PARAMS < <(echo "$CONFIG_DEB_INSTALL_JSON" | jq -r '.[].params')

# ==========================================
# 3. LOGIQUE INTERFACE
# ==========================================
do_deb_install_menu(){
  local cursor selected_ids visible_indices

  cursor=0
  selected_ids=()

  while true; do
      # On filtre les indices visibles via Bash (très rapide)
      visible_indices=()
      for i in "${!ALL_DEB_INSTALL_IDS[@]}"; do
          if ! check_deb_status "${ALL_DEB_INSTALL_TYPES[$i]}" "${ALL_DEB_INSTALL_PARAMS[$i]}"; then
              visible_indices+=("$i")
          fi
      done

      # Sortie si vide
      [[ ${#visible_indices[@]} -eq 0 ]] && echo -e "${COLOR_GREEN}Tout est OK !${NONE}" && exit 0

      # Affichage
      clear
      echo -e "${COLOR_LIGHT_BLUE}====[ FROGG DEPLOY ]====${NONE}"
      echo -e "Flèches: Naviguer | Espace: Sélectionner | Entrée: Lancer | ${COLOR_LIGHT_RED}q: Quitter ou Ctrl+C${NONE}\n"

      for i in "${!visible_indices[@]}"; do
          idx=${visible_indices[$i]}
          id=${ALL_DEB_INSTALL_IDS[$idx]}

          [[ $i -eq $cursor ]] && echo -ne "${COLOR_CYAN}> ${NONE}" || echo -ne "  "

          is_selected=false
          [[ " ${selected_ids[*]} " == *" $id "* ]] && is_selected=true

          [[ $is_selected == true ]] && echo -e "[X] ${ALL_DEB_INSTALL_LABELS[$idx]}" || echo -e "[ ] ${ALL_DEB_INSTALL_LABELS[$idx]}"
      done

      # Lecture touche
      IFS= read -rsn1 key
      [[ $key == "q" ]] && exit 0
      if [[ $key == $'\x1b' ]]; then
          read -rsn2 key
          case $key in
              '[A') ((cursor--)); [[ $cursor -lt 0 ]] && cursor=$((${#visible_indices[@]} - 1)) ;;
              '[B') ((cursor++)); [[ $cursor -ge ${#visible_indices[@]} ]] && cursor=0 ;;
          esac
      elif [[ $key == "" ]]; then break
      elif [[ $key == " " ]]; then
          target_id=${ALL_DEB_INSTALL_IDS[${visible_indices[$cursor]}]}
          if [[ " ${selected_ids[*]} " == *" $target_id "* ]]; then
              selected_ids=("${selected_ids[@]//$target_id/}") # Décocher
          else
              selected_ids+=("$target_id") # Cocher
          fi
      fi
  done

  # ==========================================
  # 5. EXÉCUTION
  # ==========================================
  clear
# On compte le nombre d'éléments dans le tableau des IDs sélectionnés
nb_actions=${#selected_ids[@]}

if [[ $nb_actions -eq 0 ]]; then
    msg_warning "Aucune action sélectionnée. Sortie du script."
    exit 0
fi

msg_info "Lancement de $nb_actions tâche(s) sélectionnée(s)..."
  for id in "${selected_ids[@]}"; do
      [[ -z "$id" ]] && continue
      # Trouver l'index original pour cet ID
      for i in "${!ALL_DEB_INSTALL_IDS[@]}"; do
          if [[ "${ALL_DEB_INSTALL_IDS[$i]}" == "$id" ]]; then
              echo -e "${COLOR_YELLOW}--- ${ALL_DEB_INSTALL_LABELS[$i]} ---${NONE}"
              do_deb_install_action "${ALL_DEB_INSTALL_TYPES[$i]}" "${ALL_DEB_INSTALL_PARAMS[$i]}"
          fi
      done
  done

  msg_success "Terminé ! ✨"

  pause

  . "${WELCOME_SCRIPT_PATH}/777-welcome.sh"
}

do_deb_install_menu