#!/usr/bin/env bash

module_description() {
  printf "Additional Software (Obsidian, Neovim, VS Code, Spotify, Brave, Chromium, VLC, PipeWire, Docker, Blender, opencode)\n"
}

module_required() { return 1; }
module_should_skip() { return 1; }

module_prereqs() {
  return 0
}

module_main() {
  log_section "Optional Software Selection"

  tui_bold "Select optional software to install:"
  tui_info "Use space (gum) or enter indices (basic) to select."
  printf '\n'

  local choices
  choices="$(
    tui_multiselect "Software Selection" \
      "Obsidian" \
      "Neovim" \
      "Visual Studio Code" \
      "Spotify" \
      "Brave Browser" \
      "Chromium" \
      "VLC" \
      "PipeWire Tools" \
      "Docker" \
      "Blender" \
      "opencode"
  )"

  if [[ -z "$choices" ]]; then
    log_info "No optional software selected"
    return 0
  fi

  log_info "Selected: $(printf '%s' "$choices" | tr '\n' ' ')"

  while IFS= read -r selection; do
    [[ -z "$selection" ]] && continue
    local module_script="$OMERON_PROJECT_DIR/modules/optional/packages/$(echo "$selection" | tr '[:upper:]' '[:lower:]' | tr ' ' '-').sh"
    if [[ -f "$module_script" ]]; then
      log_info "Running installer for: $selection"
      module_run "$module_script"
    else
      log_warn "No installer found for: $selection"
      local pkg_name="${selection,,}"
      pkg_name="${pkg_name// /-}"
      install_standard_package "$selection" "$pkg_name"
    fi
  done <<< "$choices"

  log_success "Optional software installation complete"
}

install_standard_package() {
  local display_name="$1"
  local pkg_name="$2"

  if tui_confirm "Install $display_name (searching pacman)?"; then
    if pacman -Si "$pkg_name" >/dev/null 2>&1; then
      install_pacman "$pkg_name"
      log_success "$display_name installed"
    else
      log_info "$pkg_name not in pacman, trying AUR..."
      install_aur "$pkg_name" 2>/dev/null || log_warn "Could not install $display_name"
    fi
  fi
}
