#!/usr/bin/env bash
# Dial CLI installer — installs @getdial/cli from npm.
set -euo pipefail

PKG="@getdial/cli"
MIN_NODE_MAJOR=22

red()    { printf "\033[31m%s\033[0m\n" "$*"; }
green()  { printf "\033[32m%s\033[0m\n" "$*"; }
yellow() { printf "\033[33m%s\033[0m\n" "$*"; }

case "$(uname -s)" in
  Darwin|Linux) ;;
  *) red "Unsupported OS: $(uname -s). Dial CLI supports macOS and Linux only."; exit 1 ;;
esac

if ! command -v node >/dev/null 2>&1; then
  red "node is not installed. Install Node.js ${MIN_NODE_MAJOR}+ from https://nodejs.org and try again."
  exit 1
fi
NODE_MAJOR="$(node -p 'process.versions.node.split(".")[0]')"
if [ "$NODE_MAJOR" -lt "$MIN_NODE_MAJOR" ]; then
  red "Node $(node -v) is too old. Dial CLI requires Node ${MIN_NODE_MAJOR}+."
  exit 1
fi

if ! command -v npm >/dev/null 2>&1; then
  red "npm is not installed. Install Node.js (which includes npm) and try again."
  exit 1
fi

yellow "Installing $PKG globally from npm ..."
# @latest + --prefer-online: bypass any stale local npm metadata cache
# so a fresh install always gets the newest published version.
#
# Try a normal global install first. If the global prefix isn't writable
# (EACCES — common with a system-managed Node, or in sandboxes/containers),
# fall back to a user-local npm prefix. No sudo required.
if npm install -g "$PKG@latest" --prefer-online; then
  green "dial installed."
else
  yellow "Global install failed (the npm prefix isn't writable)."
  yellow "Falling back to a user-local prefix — no sudo needed."
  PREFIX="${DIAL_NPM_PREFIX:-$HOME/.npm-global}"
  mkdir -p "$PREFIX"
  npm config set prefix "$PREFIX"
  npm install -g "$PKG@latest" --prefer-online
  BIN="$PREFIX/bin"
  export PATH="$BIN:$PATH"
  green "dial installed to $BIN."
  echo
  yellow "Add it to your PATH so new shells find 'dial' (append to ~/.zshrc or ~/.bashrc):"
  printf '    export PATH="%s:$PATH"\n' "$BIN"
fi
echo

# ── Attribution: persist ref params write-once for the CLI to forward ──
DATA_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/dial"
mkdir -p "$DATA_DIR"
FILE="$DATA_DIR/ref-params.txt"
touch "$FILE"

# Append "key=value" only if the key isn't already present — first touch wins, so
# a later install never overwrites how the user originally arrived.
add_ref() {
  local key="$1" val="$2"
  grep -q "^${key}=" "$FILE" 2>/dev/null || printf '%s=%s\n' "$key" "$val" >> "$FILE"
}

# Ensure an attribution id exists even for a bare install (no browser origin).
grep -q "^dial_attribution_id=" "$FILE" 2>/dev/null || add_ref 'dial_attribution_id' "$(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid 2>/dev/null || echo "cli-$(date +%s)-$RANDOM")"

dial doctor || true
