#!/usr/bin/env bash
set -euo pipefail

# --- Config ---
VERSION="${HUIMEI_VERSION:-latest}"
PACKAGE="huimei"
OFFICIAL_VERSION="0.6.50"
OFFICIAL_WHEEL_URL="${HUIMEI_WHEEL_URL:-huimei==0.6.50}"
MIN_PYTHON="3.10"
MAX_PYTHON_EXCLUSIVE="3.15"
UV_VERSION="0.11.23"
UV_INSTALLER_SHA256="f2217f2fe451df47895a580143e2707b59c995186b47dfaa2e92b1aedf0dc764"
HUIMEI_PIP_INDEX_URL="${HUIMEI_PIP_INDEX_URL:-}"
if [[ -n "$HUIMEI_PIP_INDEX_URL" ]]; then
  export UV_INDEX_URL="$HUIMEI_PIP_INDEX_URL"
  export PIP_INDEX_URL="$HUIMEI_PIP_INDEX_URL"
else
  unset UV_INDEX_URL PIP_INDEX_URL
fi

# --- Colors ---
if [[ -t 1 ]]; then
  GREEN='\033[0;32m' RED='\033[0;31m' YELLOW='\033[0;33m'
  CYAN='\033[0;36m' DIM='\033[2m' BOLD='\033[1m' RESET='\033[0m'
else
  GREEN='' RED='' YELLOW='' CYAN='' DIM='' BOLD='' RESET=''
fi

ok()   { echo -e "  ${GREEN}✓${RESET} $1"; }
fail() { echo -e "  ${RED}✗${RESET} $1"; }
warn() { echo -e "  ${YELLOW}⚠${RESET} $1"; }
info() { echo -e "  ${CYAN}ℹ${RESET} $1"; }
dim()  { echo -e "  ${DIM}$1${RESET}"; }
step() { echo -e "\n${BOLD}[$1]${RESET} $2"; }

# --- Parse args ---
while [[ $# -gt 0 ]]; do
  case "$1" in
    --version)
      if [[ $# -lt 2 ]]; then
        fail "--version requires a value (e.g. --version 0.6.0)"; exit 1
      fi
      VERSION="$2"; shift 2 ;;
    --help|-h)
      echo "Usage: curl -fsSL https://huimei.smaroot.tech/install.sh | bash"
      echo "       bash install.sh [--version VERSION]"
      echo ""
      echo "Options:"
      echo "  --version VERSION  Install a specific version (e.g. 0.6.0)"
      echo "  --help             Show this help message"
      exit 0 ;;
    *) fail "Unknown option: $1"; exit 1 ;;
  esac
done

# --- Banner ---
echo -e "${CYAN}"
cat << 'EOF'
  _   _       _                _ 
 | | | |_   _(_)_ __ ___   ___(_)
 | |_| | | | | | '_ ` _ \ / _ \ |
 |  _  | |_| | | | | | | |  __/ |
 |_| |_|\__,_|_|_| |_| |_|\___|_|
  Social Media Automation CLI
EOF
echo -e "${RESET}"

if [[ "$VERSION" != "latest" ]]; then
  info "Installing version: ${BOLD}${VERSION}${RESET}"
fi

# ============================================================
# [1/5] Check OS
# ============================================================
step "1/5" "Checking operating system..."

OS="$(uname -s)"
ARCH="$(uname -m)"

case "$OS" in
  Darwin) ok "macOS ${ARCH} detected"
    if [[ "$ARCH" == "arm64" ]] && ! /usr/bin/pgrep -q oahd 2>/dev/null; then
      dim "Apple Silicon native — no Rosetta needed"
    fi ;;
  Linux)  ok "Linux ${ARCH} detected" ;;
  MINGW*|MSYS*|CYGWIN*|Windows_NT)
    fail "Windows detected. Use PowerShell instead:"
    echo ""
    echo "  python -m pip install --user pipx"
    echo "  python -m pipx ensurepath"
    echo "  python -m pipx install huimei"
    echo ""
    exit 1 ;;
  *) fail "Unsupported OS: $OS"; exit 1 ;;
esac

# ============================================================
# [2/5] Check Python 3.10+
# ============================================================
step "2/5" "Checking Python version..."

PYTHON=""
USE_UV_TOOL=false
for cmd in python3.14 python3.13 python3.12 python3.11 python3.10 python3 python; do
  if command -v "$cmd" &>/dev/null; then
    ver="$("$cmd" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null || true)"
    if [[ -n "$ver" ]] && "$cmd" -c "import sys; v=sys.version_info[:2]; exit(0 if (3,10) <= v < (3,15) else 1)" 2>/dev/null; then
      PYTHON="$cmd"
      break
    fi
  fi
done

if [[ -z "$PYTHON" ]]; then
  info "No compatible system Python found; installing an isolated Python 3.13..."
  export PATH="$HOME/.local/bin:$PATH"
  if ! command -v uv &>/dev/null; then
    command -v curl &>/dev/null || { fail "curl is required to install isolated Python."; exit 1; }
    uv_installer="$(mktemp)"
    trap 'rm -f "${uv_installer:-}"' EXIT
    curl -fsSL "https://astral.sh/uv/${UV_VERSION}/install.sh" -o "$uv_installer"
    if command -v shasum &>/dev/null; then
      uv_installer_digest="$(shasum -a 256 "$uv_installer" | awk '{print $1}')"
    elif command -v sha256sum &>/dev/null; then
      uv_installer_digest="$(sha256sum "$uv_installer" | awk '{print $1}')"
    else
      fail "SHA-256 verification tool is required."; exit 1
    fi
    [[ "$uv_installer_digest" == "$UV_INSTALLER_SHA256" ]] || { fail "uv installer integrity check failed."; exit 1; }
    UV_UNMANAGED_INSTALL="$HOME/.local/bin" sh "$uv_installer"
  fi
  uv python install 3.13
  PYTHON="$(uv python find 3.13)"
  [[ -x "$PYTHON" ]] || { fail "Failed to provision isolated Python 3.13."; exit 1; }
  USE_UV_TOOL=true
fi

py_ver="$("$PYTHON" --version 2>&1)"
ok "${py_ver} — $(command -v "$PYTHON")"

# ============================================================
# [3/5] Install pipx
# ============================================================
step "3/5" "Checking pipx..."

ensure_pipx_path() {
  if ! command -v pipx &>/dev/null; then
    export PATH="$HOME/.local/bin:$PATH"
  fi
}

if [[ "$USE_UV_TOOL" == true ]]; then
  ok "uv tool environment ready"
elif command -v pipx &>/dev/null; then
  ok "pipx already installed"
else
  ensure_pipx_path
  if command -v pipx &>/dev/null; then
    ok "pipx found in ~/.local/bin"
  else
    info "Installing pipx..."
    pipx_installed=false

    # Strategy 1: System package manager (avoids PEP 668 on Homebrew/Ubuntu 23.04+/Fedora 38+/Arch)
    if [[ "$OS" == "Darwin" ]] && command -v brew &>/dev/null; then
      if brew install pipx 2>/dev/null; then
        pipx_installed=true
      fi
    elif command -v apt &>/dev/null; then
      if sudo -n apt install -y pipx 2>/dev/null; then
        pipx_installed=true
      fi
    elif command -v dnf &>/dev/null; then
      if sudo -n dnf install -y pipx 2>/dev/null; then
        pipx_installed=true
      fi
    elif command -v pacman &>/dev/null; then
      if sudo -n pacman -S --noconfirm python-pipx 2>/dev/null; then
        pipx_installed=true
      fi
    fi

    # Strategy 2: pip install --user (works on older distros without PEP 668)
    if [[ "$pipx_installed" == false ]]; then
      "$PYTHON" -m pip install --user pipx 2>&1 | tail -1 | while read -r line; do dim "$line"; done || true
    fi

    export PATH="$HOME/.local/bin:$PATH"
    if command -v pipx &>/dev/null; then
      ok "pipx installed"
    else
      fail "pipx not available."
      echo ""
      info "Install pipx manually, then retry:"
      case "$OS" in
        Darwin)
          echo "  brew install pipx"
          echo "  pipx ensurepath" ;;
        Linux)
          echo "  python3 -m pip install --user pipx"
          echo "  python3 -m pipx ensurepath" ;;
      esac
      exit 1
    fi
  fi
fi

# ============================================================
# [4/5] Install huimei
# ============================================================
step "4/5" "Installing ${PACKAGE}..."

pkg_spec="${OFFICIAL_WHEEL_URL}"
[[ "$VERSION" != "latest" ]] && pkg_spec="${PACKAGE}==${VERSION}"

installed=false
WORKER_WAS_RUNNING=false
EXISTING_HUIMEI="$(command -v huimei 2>/dev/null || true)"
if [[ -z "$EXISTING_HUIMEI" ]] && [[ -x "$HOME/.local/bin/huimei" ]]; then
  EXISTING_HUIMEI="$HOME/.local/bin/huimei"
fi
if [[ -z "$EXISTING_HUIMEI" ]] && command -v pipx &>/dev/null; then
  EXISTING_BIN_DIR="$(pipx environment --value PIPX_BIN_DIR 2>/dev/null || true)"
  [[ -x "$EXISTING_BIN_DIR/huimei" ]] && EXISTING_HUIMEI="$EXISTING_BIN_DIR/huimei"
fi
if [[ -n "$EXISTING_HUIMEI" ]] && "$EXISTING_HUIMEI" worker status --json 2>/dev/null | grep -Eq '"running"[[:space:]]*:[[:space:]]*true'; then
  WORKER_WAS_RUNNING=true
  info "Stopping the existing publishing device before upgrade..."
  "$EXISTING_HUIMEI" worker stop --json >/dev/null
  if "$EXISTING_HUIMEI" worker status --json 2>/dev/null | grep -Eq '"running"[[:space:]]*:[[:space:]]*true'; then
    fail "Unable to stop the existing publishing device. Installation cancelled."
    exit 1
  fi
fi

if [[ "$USE_UV_TOOL" == true ]]; then
  if uv tool list 2>/dev/null | grep -q "^${PACKAGE} "; then
    info "Upgrading existing installation..."
    if [[ "$VERSION" == "latest" ]]; then
      if uv tool install --force --python "$PYTHON" "$pkg_spec"; then installed=true; fi
    elif uv tool install --force --python "$PYTHON" "$pkg_spec"; then
      installed=true
    fi
  elif uv tool install --python "$PYTHON" "$pkg_spec"; then
    installed=true
  fi
elif command -v pipx &>/dev/null; then
  PIPX_HOME_DIR="$(pipx environment --value PIPX_HOME 2>/dev/null || true)"
  if pipx list 2>/dev/null | grep -q "package ${PACKAGE}"; then
    info "Upgrading existing installation..."
    if [[ -n "$HUIMEI_PIP_INDEX_URL" ]]; then
      if pipx runpip "$PACKAGE" install --upgrade --no-cache-dir --index-url "$HUIMEI_PIP_INDEX_URL" "$pkg_spec"; then
        installed=true
      fi
    elif pipx runpip "$PACKAGE" install --upgrade --no-cache-dir "$pkg_spec"; then
      installed=true
    fi
  else
    stale_venv="${PIPX_HOME_DIR:-$HOME/.local/pipx}/venvs/${PACKAGE}"
    if [[ -d "$stale_venv" ]]; then
      info "Removing an incomplete previous ${PACKAGE} environment..."
      rm -rf "$stale_venv"
    fi
    if [[ -n "$HUIMEI_PIP_INDEX_URL" ]]; then
      if pipx install --python "$PYTHON" --pip-args=--no-cache-dir --index-url "$HUIMEI_PIP_INDEX_URL" "$pkg_spec"; then
        installed=true
      fi
    elif pipx install --python "$PYTHON" --pip-args=--no-cache-dir "$pkg_spec"; then
      installed=true
    fi
  fi
fi

if [[ "$installed" == false ]]; then
  fail "pipx install failed."
  info "Please retry after checking network and PyPI access:"
  echo "  pipx reinstall ${PACKAGE}"
  exit 1
fi

# Persist pipx's application directory for future shells. This command is
# idempotent and complements the explicit shell-specific update below.
if [[ "$USE_UV_TOOL" == true ]]; then
  uv tool update-shell >/dev/null 2>&1 || true
  PIPX_BIN_DIR="$(uv tool dir --bin 2>/dev/null || true)"
else
  pipx ensurepath >/dev/null 2>&1 || "$PYTHON" -m pipx ensurepath >/dev/null 2>&1 || true
  PIPX_BIN_DIR="$(pipx environment --value PIPX_BIN_DIR 2>/dev/null || true)"
fi
if [[ -z "$PIPX_BIN_DIR" ]]; then
  PIPX_BIN_DIR="$HOME/.local/bin"
fi

# --- Locate the huimei binary ---
HUIMEI_BIN=""
if [[ -f "$PIPX_BIN_DIR/huimei" ]]; then
  HUIMEI_BIN="$PIPX_BIN_DIR/huimei"
elif command -v huimei &>/dev/null; then
  HUIMEI_BIN="$(command -v huimei)"
else
  # Search common install locations
  USER_BASE="$("$PYTHON" -m site --user-base 2>/dev/null || echo "$HOME/.local")"
  for dir in "$PIPX_BIN_DIR" "$HOME/.local/bin" "${USER_BASE}/bin" "/usr/local/bin"; do
    if [[ -f "$dir/huimei" ]]; then
      HUIMEI_BIN="$dir/huimei"
      break
    fi
  done
fi

if [[ -z "$HUIMEI_BIN" ]]; then
  fail "Installation failed. Try manually: pipx install ${pkg_spec}"
  exit 1
fi

ok "${PACKAGE} installed — ${HUIMEI_BIN}"

if [[ "$WORKER_WAS_RUNNING" == true ]]; then
  if ! "$HUIMEI_BIN" worker start --json >/dev/null; then
    fail "CLI installed, but the publishing device could not restart. Run: huimei login"
    exit 1
  fi
  ok "Publishing device restarted with the new version"
fi

# --- Ensure the bin directory is on PATH (persist across sessions) ---
BIN_DIR="$(dirname "$HUIMEI_BIN")"

# Resolve ~ for comparison (expand $HOME in BIN_DIR for display)
BIN_DIR_DISPLAY="${BIN_DIR/#$HOME/\~}"

add_to_path_if_needed() {
  # Reload with: exec "$SHELL" -l
  # Check if BIN_DIR is already in current PATH
  if echo "$PATH" | tr ':' '\n' | grep -qx "$BIN_DIR"; then
    return 0   # already on PATH, nothing to do
  fi

  local added_to=""

  # Only write to rc files relevant to the user's current shell
  local shell_name
  shell_name="$(basename "${SHELL:-/bin/bash}")"
  local rcs=()
  case "$shell_name" in
    zsh)  rcs=("$HOME/.zshrc") ;;
    bash) rcs=("$HOME/.bashrc") ;;
    *)    rcs=("$HOME/.profile") ;;
  esac
  # On macOS, default shell is zsh — ensure .zshrc is targeted
  if [[ "$(uname -s)" == "Darwin" ]] && [[ "$shell_name" != "zsh" ]]; then
    rcs+=("$HOME/.zshrc")
  fi

  for rc in "${rcs[@]}"; do
    # Skip if this rc file already contains the PATH entry
    if [[ -f "$rc" ]] && grep -qF "export PATH=\"${BIN_DIR}:" "$rc" 2>/dev/null; then
      continue
    fi
    # Check write permission
    if [[ -f "$rc" ]] && [[ ! -w "$rc" ]]; then
      warn "Cannot write to ${rc/#$HOME/\~} (permission denied), skipping"
      continue
    fi
    echo "" >> "$rc"
    echo "# Added by huimei installer" >> "$rc"
    echo "export PATH=\"${BIN_DIR}:\$PATH\"" >> "$rc"
    added_to="${added_to} ${rc/#$HOME/\~}"
  done

  # Also fix current session
  export PATH="${BIN_DIR}:$PATH"

  if [[ -n "$added_to" ]]; then
    ok "Added ${BIN_DIR_DISPLAY} to PATH in:${added_to}"
    info "Run: ${BOLD}source ${rcs[0]/#$HOME/\~}${RESET}, ${BOLD}exec \"\$SHELL\" -l${RESET}, or open a new terminal"
  fi
}

add_to_path_if_needed

# ============================================================
# [5/5] Check local Chrome
# ============================================================
step "5/5" "Checking local Chrome browser..."

if [[ "$OS" == "Darwin" ]] && [[ -x "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" ]]; then
  ok "Google Chrome detected"
elif command -v google-chrome >/dev/null 2>&1 || command -v google-chrome-stable >/dev/null 2>&1 || command -v chromium >/dev/null 2>&1; then
  ok "Chrome/Chromium detected"
else
  warn "Google Chrome was not found. Cloud publishing is still available."
  info "Install Chrome before using local or auto publishing mode."
fi

# ============================================================
# Verify & Done
# ============================================================
echo ""
if huimei_ver="$("$HUIMEI_BIN" version 2>&1)"; then
  ok "Verified executable: ${BIN_DIR_DISPLAY}/huimei"
else
  fail "Installed executable could not start: ${HUIMEI_BIN}"
  exit 1
fi
if [[ "$VERSION" == "latest" ]] && [[ "$huimei_ver" != *"$OFFICIAL_VERSION"* ]]; then
  fail "Installed version does not match official release ${OFFICIAL_VERSION}."
  exit 1
fi
if command -v huimei >/dev/null 2>&1 && huimei_ver="$(huimei version 2>&1)"; then
  ok "Verified: ${BOLD}${huimei_ver}${RESET}"
else
  warn "Installed successfully, but this terminal has not reloaded PATH yet."
  info "Run: ${BOLD}exec \"\$SHELL\" -l${RESET} or open a new terminal"
fi

echo ""
echo -e "${GREEN}${BOLD}  ✅ huimei is ready!${RESET}"
echo ""
echo -e "  Quick start:"
echo -e "  ${DIM}─────────────────────────────────────────${RESET}"
echo -e "  ${BOLD}huimei login${RESET}          ${DIM}# 登录账号${RESET}"
echo -e "  ${BOLD}huimei platforms${RESET}      ${DIM}# 查看支持的平台${RESET}"
echo -e "  ${BOLD}huimei publish --help${RESET} ${DIM}# 发布内容${RESET}"
echo -e "  ${DIM}─────────────────────────────────────────${RESET}"
echo ""
