#!/usr/bin/env bash

BRT_DEPS_MANIFEST="${HOME}/.brt/installed-deps"

# Auto-installed on setup
BRT_AUTO_DEP_CMDS=(mpv chafa yt-dlp)
# Optional — installed only with BRT_FULL_DEPS=1
BRT_OPTIONAL_DEP_CMDS=(ffmpeg)

brt_deps_info() {
  if declare -f brt_info &>/dev/null; then brt_info "$@"; else printf '\033[36m●\033[0m %s\n' "$*"; fi
}

brt_deps_ok() {
  if declare -f brt_ok &>/dev/null; then brt_ok "$@"; else printf '\033[32m✓\033[0m %s\n' "$*"; fi
}

brt_deps_warn() {
  if declare -f brt_warn &>/dev/null; then brt_warn "$@"; else printf '\033[33m!\033[0m %s\n' "$*" >&2; fi
}

brt_deps_record() {
  local mgr="$1"
  shift
  local pkg

  [[ $# -gt 0 ]] || return 0
  mkdir -p "${HOME}/.brt"
  touch "$BRT_DEPS_MANIFEST"

  for pkg in "$@"; do
    [[ -n "$pkg" ]] || continue
    grep -qxF "${mgr}:${pkg}" "$BRT_DEPS_MANIFEST" 2>/dev/null && continue
    echo "${mgr}:${pkg}" >> "$BRT_DEPS_MANIFEST"
  done
}

brt_deps_missing_cmds() {
  local -a list=("$@")
  local cmd
  local -a out=()
  for cmd in "${list[@]}"; do
    command -v "$cmd" &>/dev/null || out+=("$cmd")
  done
  ((${#out[@]})) && printf '%s\n' "${out[@]}"
}

brt_deps_install_pkgs() {
  local mgr="$1"
  shift
  local -a pkgs=()

  while [[ $# -gt 0 ]]; do
    pkgs+=("$1")
    shift
  done

  ((${#pkgs[@]} == 0)) && return 0

  case "$mgr" in
    brew)
      brt_deps_info "Installing via Homebrew: ${pkgs[*]}"
      brew install "${pkgs[@]}" && brt_deps_record brew "${pkgs[@]}"
      ;;
    apt)
      brt_deps_info "Installing via apt: ${pkgs[*]}"
      sudo apt-get update -qq
      sudo apt-get install -y "${pkgs[@]}" && brt_deps_record apt "${pkgs[@]}"
      ;;
    dnf)
      brt_deps_info "Installing via dnf: ${pkgs[*]}"
      sudo dnf install -y "${pkgs[@]}" && brt_deps_record dnf "${pkgs[@]}"
      ;;
    pacman)
      brt_deps_info "Installing via pacman: ${pkgs[*]}"
      sudo pacman -S --noconfirm "${pkgs[@]}" && brt_deps_record pacman "${pkgs[@]}"
      ;;
    zypper)
      brt_deps_info "Installing via zypper: ${pkgs[*]}"
      sudo zypper install -y "${pkgs[@]}" && brt_deps_record zypper "${pkgs[@]}"
      ;;
  esac
}

brt_install_media_dependencies() {
  local -a auto_missing=() optional_missing=() to_install=()
  local cmd mgr pkgs_line

  brt_deps_info "Checking media dependencies..."

  while IFS= read -r cmd; do
    [[ -n "$cmd" ]] && auto_missing+=("$cmd")
  done < <(brt_deps_missing_cmds "${BRT_AUTO_DEP_CMDS[@]}")

  while IFS= read -r cmd; do
    [[ -n "$cmd" ]] && optional_missing+=("$cmd")
  done < <(brt_deps_missing_cmds "${BRT_OPTIONAL_DEP_CMDS[@]}")

  if [[ "${BRT_FULL_DEPS:-}" == "1" ]]; then
    to_install=()
    brt_arr_append to_install auto_missing
    brt_arr_append to_install optional_missing
  else
    to_install=()
    brt_arr_append to_install auto_missing
  fi

  if ((${#to_install[@]} == 0)); then
    if ((${#optional_missing[@]} == 0)); then
      brt_deps_ok "Media dependencies ready"
    else
      brt_deps_ok "Required media tools ready"
      brt_deps_info "Optional (install when needed): ${optional_missing[*]}"
    fi
    return 0
  fi

  if [[ "${BRT_SKIP_DEPS:-}" == "1" ]]; then
    brt_deps_warn "Missing media tools: ${to_install[*]} (set BRT_SKIP_DEPS=0 to auto-install)"
    return 0
  fi

  pkgs_line="${to_install[*]}"

  if command -v brew &>/dev/null; then
    if brt_deps_install_pkgs brew "${to_install[@]}"; then
      :
    else
      brt_deps_warn "Some Homebrew packages failed to install"
    fi
    ((${#optional_missing[@]} > 0 && "${BRT_FULL_DEPS:-}" != "1")) \
      && brt_deps_info "Optional later: ${optional_missing[*]} (brew install …, or BRT_FULL_DEPS=1)"
    return 0
  fi

  if command -v apt-get &>/dev/null && command -v sudo &>/dev/null; then
    brt_deps_install_pkgs apt "${to_install[@]}" || brt_deps_warn "apt install failed"
    return 0
  fi

  if command -v dnf &>/dev/null && command -v sudo &>/dev/null; then
    brt_deps_install_pkgs dnf "${to_install[@]}" || brt_deps_warn "dnf install failed"
    return 0
  fi

  if command -v pacman &>/dev/null && command -v sudo &>/dev/null; then
    brt_deps_install_pkgs pacman "${to_install[@]}" || brt_deps_warn "pacman install failed"
    return 0
  fi

  if command -v zypper &>/dev/null && command -v sudo &>/dev/null; then
    brt_deps_install_pkgs zypper "${to_install[@]}" || brt_deps_warn "zypper install failed"
    return 0
  fi

  brt_deps_warn "Could not detect a package manager. Install manually: ${pkgs_line}"
}

brt_uninstall_media_dependencies() {
  local line mgr pkg removed=0

  [[ -f "$BRT_DEPS_MANIFEST" ]] || return 0

  brt_deps_info "Removing packages installed by brt..."

  while IFS= read -r line || [[ -n "$line" ]]; do
    [[ -z "$line" || "$line" == \#* ]] && continue
    mgr="${line%%:*}"
    pkg="${line#*:}"
    [[ -n "$mgr" && -n "$pkg" && "$mgr" != "$pkg" ]] || continue

    case "$mgr" in
      brew)
        if command -v brew &>/dev/null && brew list --formula "$pkg" &>/dev/null; then
          if brew uninstall "$pkg" 2>/dev/null; then
            brt_deps_ok "Removed ${pkg} (Homebrew)"
            ((removed++)) || true
          else
            brt_deps_warn "Could not remove ${pkg} (Homebrew)"
          fi
        fi
        ;;
      apt)
        if command -v apt-get &>/dev/null && command -v sudo &>/dev/null; then
          if dpkg -l "$pkg" 2>/dev/null | grep -q '^ii'; then
            if sudo apt-get remove -y "$pkg" &>/dev/null; then
              brt_deps_ok "Removed ${pkg} (apt)"
              ((removed++)) || true
            else
              brt_deps_warn "Could not remove ${pkg} (apt)"
            fi
          fi
        fi
        ;;
      dnf)
        if command -v dnf &>/dev/null && command -v sudo &>/dev/null; then
          if rpm -q "$pkg" &>/dev/null; then
            if sudo dnf remove -y "$pkg" &>/dev/null; then
              brt_deps_ok "Removed ${pkg} (dnf)"
              ((removed++)) || true
            else
              brt_deps_warn "Could not remove ${pkg} (dnf)"
            fi
          fi
        fi
        ;;
      pacman)
        if command -v pacman &>/dev/null && command -v sudo &>/dev/null; then
          if pacman -Q "$pkg" &>/dev/null; then
            if sudo pacman -R --noconfirm "$pkg" &>/dev/null; then
              brt_deps_ok "Removed ${pkg} (pacman)"
              ((removed++)) || true
            else
              brt_deps_warn "Could not remove ${pkg} (pacman)"
            fi
          fi
        fi
        ;;
      zypper)
        if command -v zypper &>/dev/null && command -v sudo &>/dev/null; then
          if rpm -q "$pkg" &>/dev/null; then
            if sudo zypper remove -y "$pkg" &>/dev/null; then
              brt_deps_ok "Removed ${pkg} (zypper)"
              ((removed++)) || true
            else
              brt_deps_warn "Could not remove ${pkg} (zypper)"
            fi
          fi
        fi
        ;;
    esac
  done < "$BRT_DEPS_MANIFEST"

  rm -f "$BRT_DEPS_MANIFEST"

  if [[ "$removed" -eq 0 ]]; then
    brt_deps_info "No tracked packages to remove"
  fi
}
