#!/usr/bin/env bash
# brt installer — pipe via: curl -fsSL https://brt.sushii.dev/install.sh | sh
[ -n "${BASH_VERSION:-}" ] || exec bash -s "$@"
set -euo pipefail

BRT_INSTALL_DIR="${BRT_INSTALL_DIR:-${HOME}/.local/share/brt}"
BRT_BIN_DIR="${BRT_BIN_DIR:-${HOME}/.local/bin}"
BRT_BASE_URL="${BRT_BASE_URL:-https://brt.sushii.dev}"

info()  { printf '\033[36m●\033[0m %s\n' "$*"; }
ok()    { printf '\033[32m✓\033[0m %s\n' "$*"; }
warn()  { printf '\033[33m!\033[0m %s\n' "$*" >&2; }
error() { printf '\033[31m✗\033[0m %s\n' "$*" >&2; exit 1; }

_brt_installer_os_windows() {
  [[ "${OS:-}" == "Windows_NT" ]] && return 0
  case "$(uname -s 2>/dev/null)" in
    MINGW*|MSYS*|CYGWIN*) return 0 ;;
  esac
  return 1
}

if _brt_installer_os_windows; then
  warn "This installer is for macOS and Linux."
  info "On Windows, use:"
  printf '  irm https://brt.sushii.dev/win/install.ps1 | iex\n'
  exit 1
fi

load_progress_bar() {
  local root="${1:-}"
  if [[ -n "$root" && -f "${root}/lib/progress.sh" ]]; then
    # shellcheck source=/dev/null
    source "${root}/lib/progress.sh"
    return 0
  fi

  local tmp
  tmp=$(mktemp)
  curl -fsSL \
    -H 'Cache-Control: no-cache' \
    -H 'Pragma: no-cache' \
    "${BRT_BASE_URL}/lib/progress.sh" \
    -o "$tmp" || error "Failed to download ${BRT_BASE_URL}/lib/progress.sh"
  # shellcheck source=/dev/null
  source "$tmp"
  rm -f "$tmp"
}

BRT_LIB_MODULES="common progress deps ip dns portscan ping whois trace curl post headers ssl reverse edit json encode hash url grep uuid pass run serve watch listen killport du extract sysinfo publickey timestamp timer calc env which speed weather qr image video doom browse config access update uninstall"

build_install_files() {
  INSTALL_FILES=(brt)
  local f
  for f in ${BRT_LIB_MODULES}; do
    INSTALL_FILES+=("lib/${f}.sh")
  done
  INSTALL_FILES+=(lib/access.py lib/media.py lib/browse.py version)
}

fetch() {
  local path="$1"
  local dest="${BRT_INSTALL_DIR}/${path}"
  mkdir -p "$(dirname "$dest")"
  curl -fsSL \
    -H 'Cache-Control: no-cache' \
    -H 'Pragma: no-cache' \
    "${BRT_BASE_URL}/${path}" \
    -o "$dest" || error "Failed to download ${BRT_BASE_URL}/${path}"
}

fetch_remote_version() {
  curl -fsSL \
    -H 'Cache-Control: no-cache' \
    -H 'Pragma: no-cache' \
    "${BRT_BASE_URL}/version" \
    | tr -d '[:space:]'
}

read_installed_version() {
  if [[ -f "${BRT_INSTALL_DIR}/version" ]]; then
    tr -d '[:space:]' < "${BRT_INSTALL_DIR}/version"
  else
    grep '^_BRT_EMBEDDED_VERSION=' "${BRT_INSTALL_DIR}/brt" 2>/dev/null | head -1 | cut -d'"' -f2
  fi
}

verify_install_version() {
  local expected="$1"
  local installed embedded

  installed=$(read_installed_version)
  embedded=$(grep '^_BRT_EMBEDDED_VERSION=' "${BRT_INSTALL_DIR}/brt" 2>/dev/null | head -1 | cut -d'"' -f2)

  [[ -n "$installed" ]] || error "Install failed: version file missing"
  [[ "$installed" == "$expected" ]] || error "Install failed: version file is ${installed}, expected ${expected}"
  [[ "$embedded" == "$expected" ]] || error "Install failed: brt binary is ${embedded}, expected ${expected}"
}

install_from_local() {
  local root="$1"
  local path total i=0

  build_install_files
  total=${#INSTALL_FILES[@]}

  info "Installing brt from local source..."
  mkdir -p "$BRT_INSTALL_DIR/lib" "$BRT_BIN_DIR"
  load_progress_bar "$root"

  for path in "${INSTALL_FILES[@]}"; do
    ((i++)) || true
    progress_bar "$i" "$total" "$path"
    mkdir -p "$(dirname "${BRT_INSTALL_DIR}/${path}")"
    cp "${root}/${path}" "${BRT_INSTALL_DIR}/${path}"
  done

  chmod +x "$BRT_INSTALL_DIR/brt" "$BRT_INSTALL_DIR/lib/"*.sh "$BRT_INSTALL_DIR/lib/access.py" "$BRT_INSTALL_DIR/lib/media.py" "$BRT_INSTALL_DIR/lib/browse.py"
}

install_from_site() {
  local remote_version="$1"
  local path total i=0

  build_install_files
  total=${#INSTALL_FILES[@]}

  info "Downloading brt ${remote_version} from ${BRT_BASE_URL}..."

  rm -rf "$BRT_INSTALL_DIR"
  mkdir -p "$BRT_INSTALL_DIR/lib" "$BRT_BIN_DIR"
  load_progress_bar

  for path in "${INSTALL_FILES[@]}"; do
    ((i++)) || true
    progress_bar "$i" "$total" "$path"
    fetch "$path"
  done

  chmod +x "$BRT_INSTALL_DIR/brt" "$BRT_INSTALL_DIR/lib/"*.sh "$BRT_INSTALL_DIR/lib/access.py" "$BRT_INSTALL_DIR/lib/media.py" "$BRT_INSTALL_DIR/lib/browse.py"
  verify_install_version "$remote_version"
}

BRT_PATH_MARKER='# brt PATH'

shell_rc_file() {
  case "${SHELL##*/}" in
    zsh) printf '%s' "${HOME}/.zshrc" ;;
    bash)
      if [[ "$(uname -s)" == "Darwin" ]]; then
        printf '%s' "${HOME}/.bash_profile"
      else
        printf '%s' "${HOME}/.bashrc"
      fi
      ;;
    *) printf '%s' "${HOME}/.profile" ;;
  esac
}

ensure_shell_path() {
  local rc path_line
  rc=$(shell_rc_file)
  path_line="export PATH=\"${BRT_BIN_DIR}:\$PATH\""

  if [[ -f "$rc" ]] && grep -qF "$BRT_PATH_MARKER" "$rc" 2>/dev/null; then
    SHELL_RC_CONFIGURED="$rc"
    return 0
  fi

  mkdir -p "$(dirname "$rc")"
  touch "$rc"
  {
    echo ''
    echo "$BRT_PATH_MARKER"
    echo "$path_line"
  } >> "$rc"
  SHELL_RC_CONFIGURED="$rc"
  ok "Added ${BRT_BIN_DIR} to PATH in ${rc}"
}

ensure_path_priority() {
  mkdir -p "$BRT_BIN_DIR"
  ln -sf "${BRT_INSTALL_DIR}/brt" "${BRT_BIN_DIR}/brt"

  local dir p target
  IFS=':' read -ra _path_dirs <<< "$PATH"
  for dir in "${_path_dirs[@]}"; do
    [[ -n "$dir" && -d "$dir" ]] || continue
    p="${dir}/brt"
    [[ -e "$p" ]] || continue
    [[ "$p" == "${BRT_BIN_DIR}/brt" ]] && continue
    if [[ -L "$p" ]]; then
      target=$(readlink "$p" 2>/dev/null || true)
      [[ "$target" == "${BRT_INSTALL_DIR}/brt" ]] && continue
    fi
    if [[ -w "$dir" ]]; then
      rm -f "$p"
      info "Removed conflicting brt at ${p}"
    else
      warn "Could not remove conflicting brt at ${p}"
    fi
  done

  case ":${PATH}:" in
    *":${BRT_BIN_DIR}:"*) ;;
    *) ensure_shell_path ;;
  esac

  case ":${PATH}:" in
    *":${BRT_BIN_DIR}:"*) ;;
    *) export PATH="${BRT_BIN_DIR}:${PATH}" ;;
  esac
}

ensure_startup_update_check() {
  if [[ -x "${BRT_INSTALL_DIR}/brt" ]]; then
    BRT_DIR="${BRT_INSTALL_DIR}" "${BRT_INSTALL_DIR}/brt" -update-check --install-hook 2>/dev/null || true
  fi
}

install_media_dependencies() {
  # shellcheck source=/dev/null
  source "${BRT_INSTALL_DIR}/lib/deps.sh"
  brt_install_media_dependencies
}

# Piped from curl — always install from site (never local copy)
SCRIPT_PATH="${BASH_SOURCE[0]:-}"
PIPED=false
[[ -z "$SCRIPT_PATH" || "$SCRIPT_PATH" == "-" || "$SCRIPT_PATH" == /dev/fd/* || "$SCRIPT_PATH" == /dev/stdin ]] && PIPED=true

LOCAL_ROOT=""
if [[ "$PIPED" == false && -n "$SCRIPT_PATH" && -f "$SCRIPT_PATH" ]]; then
  SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)"
  if [[ -f "${SCRIPT_DIR}/brt" && -d "${SCRIPT_DIR}/lib" && -f "${SCRIPT_DIR}/install.sh" ]]; then
    LOCAL_ROOT="$SCRIPT_DIR"
  elif [[ -f "${SCRIPT_DIR}/../brt" && -d "${SCRIPT_DIR}/../lib" ]]; then
    LOCAL_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
  fi
fi

REMOTE_VERSION=""
if [[ -z "$LOCAL_ROOT" ]]; then
  REMOTE_VERSION=$(fetch_remote_version)
  [[ -n "$REMOTE_VERSION" ]] || error "Could not fetch latest version from ${BRT_BASE_URL}/version"
  info "Latest version: ${REMOTE_VERSION}"
  install_from_site "$REMOTE_VERSION"
else
  install_from_local "$LOCAL_ROOT"
  REMOTE_VERSION=$(read_installed_version)
fi

ensure_path_priority

ensure_startup_update_check

install_media_dependencies || true

ok "brt ${REMOTE_VERSION} installed to ${BRT_INSTALL_DIR}"
info "Binary: ${BRT_BIN_DIR}/brt"
echo
info "Verifying install..."
"${BRT_BIN_DIR}/brt" -version
echo
if [[ -n "${SHELL_RC_CONFIGURED:-}" ]]; then
  ok "PATH configured — open a new terminal, or run: source \"${SHELL_RC_CONFIGURED}\""
else
  ok "PATH ready (${BRT_BIN_DIR})"
fi
info "Quick test: brt -help"
