#!/usr/bin/env bash

module_description() {
  printf "System Packages - install Hyprland, GPU drivers, and all dependencies\n"
}

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

module_prereqs() {
  require pacman pacman
  is_arch || {
    tui_error "This module requires an Arch-based system"
    return 1
  }
}

module_main() {
  log_section "Package Installation"

  local groups=()
  local all_packages=()

  if ((OMERON_FRESH_INSTALL)); then
    tui_bold "Fresh install mode — installing everything"
    groups=(
      "hyprland"
      "gpu"
      "audio"
      "network"
      "fonts"
      "tools"
      "qt"
      "development"
    )
  else
    tui_bold "Existing system — checking for missing packages"
    groups=(
      "hyprland"
      "audio"
      "network"
      "tools"
    )
  fi

  for group in "${groups[@]}"; do
    local pkgs=()
    mapfile -t pkgs < <(get_group_packages "$group")
    all_packages+=("${pkgs[@]}")
  done

  readarray -t all_packages < <(remove_duplicates "${all_packages[@]}")

  local total=${#all_packages[@]}
  local existing=0
  local missing=0
  local pkg

  for pkg in "${all_packages[@]}"; do
    if is_package_installed "$pkg"; then
      ((existing++))
    else
      ((missing++))
    fi
  done

  tui_separator
  tui_bold "Package Summary"
  tui_info "Total packages:  $(tui_bold "$total")"
  tui_success "Already installed: $(tui_bold "$existing")"
  if ((missing > 0)); then
    tui_warn "To install:        $(tui_bold "$missing")"
  fi
  printf '\n'

  if ((missing == 0)); then
    tui_success "All packages already installed"
    return 0
  fi

  if ! tui_confirm "Install ${missing} missing packages?"; then
    tui_info "Package installation skipped by user"
    return 0
  fi

  if ((OMERON_FRESH_INSTALL)); then
    tui_info "Running system update first..."
    sudo_run pacman -Syu --noconfirm 2>&1 | tail -3 || true
  fi

  local pacman_pkgs=()
  local aur_pkgs=()
  local pkg

  for pkg in "${all_packages[@]}"; do
    if is_package_installed "$pkg"; then
      continue
    fi
    if pacman -Si "$pkg" >/dev/null 2>&1; then
      pacman_pkgs+=("$pkg")
    else
      aur_pkgs+=("$pkg")
    fi
  done

  if ((${#pacman_pkgs[@]})); then
    tui_info "Installing ${#pacman_pkgs[@]} pacman packages..."
    tui_spin "Installing core packages..." sudo_run pacman -S --needed --noconfirm "${pacman_pkgs[@]}"
    tui_success "Core packages installed"
  fi

  if ((${#aur_pkgs[@]})); then
    if have paru || have yay; then
      tui_info "Installing ${#aur_pkgs[@]} AUR packages..."
      install_aur "${aur_pkgs[@]}" || tui_warn "Some AUR packages may not have been installed"
    else
      tui_warn "No AUR helper found. Install manually: ${aur_pkgs[*]}"
    fi
  fi

  tui_success "Package installation complete"
  tui_info "Installed: $((missing - ${#aur_pkgs[@]}))  |  AUR/optional: ${#aur_pkgs[@]}"
}

get_group_packages() {
  local group="$1"

  case "$group" in
    hyprland)
      printf '%s\n' \
        hyprland hyprpaper hyprlock hypridle \
        waybar wofi swaync kitty \
        sddm \
        brightnessctl playerctl \
        grim slurp swappy hyprshot \
        wl-clipboard libnotify sshpass \
        hyprpolkitagent awww
      ;;

    gpu)
      gpu_packages
      printf '%s\n' \
        mesa mesa-utils \
        vulkan-tools vulkan-icd-loader \
        libva-utils
      ;;

    audio)
      printf '%s\n' \
        pipewire pipewire-pulse pipewire-alsa pipewire-jack \
        wireplumber pavucontrol helvum \
        sof-firmware
      ;;

    network)
      printf '%s\n' \
        networkmanager network-manager-applet \
        bluez bluez-utils blueman
      ;;

    fonts)
      printf '%s\n' \
        noto-fonts noto-fonts-emoji ttf-jetbrains-mono-nerd \
        otf-font-awesome ttf-nerd-fonts-symbols ttf-dejavu
      ;;

    tools)
      printf '%s\n' \
        nautilus papirus-icon-theme starship \
        python-gobject gtk3 gtk4 \
        polkit-gnome xdg-desktop-portal xdg-desktop-portal-hyprland \
        qt5ct qt6ct \
        gum
      ;;

    qt)
      printf '%s\n' \
        qt5-wayland qt6-wayland \
        qt5-base qt6-base
      ;;

    development)
      printf '%s\n' \
        git base-devel \
        zip unzip unrar \
        ripgrep fd bat lsd \
        htop btop fastfetch
      ;;
  esac
}

remove_duplicates() {
  printf '%s\n' "$@" | sort -u
}
