#!/usr/bin/env bash
# Alran Code installer · https://alran.dev
#
#   curl -fsSL https://alran.dev/install.sh | bash
#
# Installs the `alran` npm package into ~/.alran-code and puts ~/.alran-code/bin on your PATH.
# Uses your Node.js when it is a supported version (22.19+ on 22, 24.2+ on 24, 25, 26); otherwise it
# downloads Node.js 24 from nodejs.org, verifies its SHA-256 and keeps it inside the install folder.
# Nothing is installed system-wide and nothing needs sudo. Run it again to update.
#
# Environment:
#   ALRAN_INSTALL_DIR      where to install                         (default: ~/.alran-code)
#   ALRAN_VERSION          the version of `alran` to install         (default: latest)
#   ALRAN_NO_MODIFY_PATH   set to 1 to leave your shell files alone
#   ALRAN_PACKAGE          another package spec or tarball           (default: alran)
#   ALRAN_NODE_MIRROR      another Node.js download mirror           (default: https://nodejs.org/dist)
#
# Uninstall: rm -rf ~/.alran-code, then remove the "# Alran Code CLI" line and the PATH line after it
# from your shell's startup file. Your data in ~/.alran stays until you delete it.

set -euo pipefail

main() {
  local dir="${ALRAN_INSTALL_DIR:-$HOME/.alran-code}"
  local version="${ALRAN_VERSION:-latest}"
  local pkg="${ALRAN_PACKAGE:-alran}"
  local mirror="${ALRAN_NODE_MIRROR:-https://nodejs.org/dist}"
  local node_major=24

  if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
    B=$'\033[1m'; D=$'\033[2m'; V=$'\033[38;2;185;169;255m'; G=$'\033[32m'; R=$'\033[31m'; N=$'\033[0m'
  else
    B=''; D=''; V=''; G=''; R=''; N=''
  fi
  say() { printf '%s\n' "$*"; }
  step() { printf '%s›%s %s\n' "$V" "$N" "$*"; }
  fail() { printf '%sError:%s %s\n' "$R" "$N" "$*" >&2; exit 1; }

  say ""
  say "  ${B}Alran Code${N} ${D}· installer${N}"
  say ""

  # ---- system ----
  local os arch
  case "$(uname -s)" in
    Linux) os=linux ;;
    Darwin) os=darwin ;;
    MINGW* | MSYS* | CYGWIN*) fail "Windows shells are not supported by this script. Use WSL, or run: npm install -g alran" ;;
    *) fail "unsupported system $(uname -s). Install with npm instead: npm install -g alran" ;;
  esac
  case "$(uname -m)" in
    x86_64 | amd64) arch=x64 ;;
    arm64 | aarch64) arch=arm64 ;;
    *) fail "unsupported processor $(uname -m). Install with npm instead: npm install -g alran" ;;
  esac
  command -v tar >/dev/null 2>&1 || fail "tar is required"

  if command -v curl >/dev/null 2>&1; then
    fetch() { curl -fsSL --proto '=https' --tlsv1.2 "$1" -o "$2"; }
  elif command -v wget >/dev/null 2>&1; then
    fetch() { wget -q --https-only -O "$2" "$1"; }
  else
    fail "curl or wget is required"
  fi

  sha256() {
    if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1
    elif command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -d' ' -f1
    else fail "sha256sum or shasum is required to verify the Node.js download"; fi
  }

  # ---- Node.js: yours if it fits, otherwise our own copy ----
  supported() {
    local v="$1" major minor
    v="${v#v}"; major="${v%%.*}"; v="${v#*.}"; minor="${v%%.*}"
    case "$major" in
      22) [ "$minor" -ge 19 ] ;;
      24) [ "$minor" -ge 2 ] ;;
      25 | 26) return 0 ;;
      *) return 1 ;;
    esac
  }

  local node="" npm="" runtime="$dir/runtime"
  if command -v node >/dev/null 2>&1 && command -v npm >/dev/null 2>&1 && supported "$(node -v 2>/dev/null || echo v0)"; then
    node="$(command -v node)"; npm="$(command -v npm)"
    step "Using Node.js $(node -v) from ${D}$node${N}"
  elif [ -x "$runtime/bin/node" ] && supported "$("$runtime/bin/node" -v 2>/dev/null || echo v0)"; then
    node="$runtime/bin/node"; npm="$runtime/bin/npm"
    step "Using Node.js $("$node" -v) from the install folder"
  else
    local tmp; tmp="$(mktemp -d)"
    step "Downloading Node.js $node_major for $os-$arch"
    fetch "$mirror/latest-v$node_major.x/SHASUMS256.txt" "$tmp/SHASUMS256.txt" || fail "could not reach $mirror"
    local file sum
    file="$(grep -oE "node-v[0-9.]+-$os-$arch\.tar\.gz" "$tmp/SHASUMS256.txt" | head -n 1)"
    [ -n "$file" ] || fail "no Node.js $node_major build for $os-$arch"
    sum="$(grep " $file\$" "$tmp/SHASUMS256.txt" | cut -d' ' -f1)"
    fetch "$mirror/latest-v$node_major.x/$file" "$tmp/$file" || fail "download of $file failed"
    [ "$(sha256 "$tmp/$file")" = "$sum" ] || fail "checksum mismatch for $file"
    rm -rf "$runtime" && mkdir -p "$runtime"
    tar -xzf "$tmp/$file" -C "$runtime" --strip-components=1
    rm -rf "$tmp"
    node="$runtime/bin/node"; npm="$runtime/bin/npm"
    step "Node.js $("$node" -v) verified and unpacked"
  fi

  # ---- Alran Code ----
  local spec="$pkg"
  case "$pkg" in *.tgz | *.tar.gz | /* | ./* | file:*) ;; *) spec="$pkg@$version" ;; esac
  step "Installing ${B}$spec${N} into ${D}$dir${N}"
  mkdir -p "$dir/lib" "$dir/bin"
  PATH="$(dirname "$node"):$PATH" "$npm" install --global --prefix "$dir/lib" --no-fund --no-audit --loglevel=error "$spec" >/dev/null \
    || fail "npm could not install $spec. Native modules need Python and C/C++ build tools when no prebuilt binary exists."

  # the entry point is what the package's own `bin` says (cli.js at the package root today); older builds used dist/cli.js
  local pkgdir="$dir/lib/lib/node_modules/alran" cli="" rel=""
  if [ -f "$pkgdir/package.json" ]; then
    rel="$("$node" -e 'const b=JSON.parse(require("fs").readFileSync(process.argv[1],"utf8")).bin;process.stdout.write(typeof b==="string"?b:(b&&(b.alran||Object.values(b)[0]))||"")' "$pkgdir/package.json" 2>/dev/null || true)"
    [ -n "$rel" ] && cli="$pkgdir/$rel"
  fi
  [ -f "$cli" ] || cli="$pkgdir/cli.js"
  [ -f "$cli" ] || cli="$pkgdir/dist/cli.js"
  [ -f "$cli" ] || cli="$(find "$dir/lib/lib/node_modules" -maxdepth 3 \( -path '*/cli.js' -o -path '*/dist/cli.js' \) -not -path '*/node_modules/*/node_modules/*' 2>/dev/null | head -n 1)"
  [ -n "$cli" ] && [ -f "$cli" ] || fail "the installed package has no command-line entry (looked for the bin of package.json, cli.js and dist/cli.js)"

  # the launcher pins the Node.js this script chose, so a later Node switch (nvm, brew) cannot break it
  cat >"$dir/bin/alran" <<LAUNCHER
#!/bin/sh
# Alran Code launcher (written by https://alran.dev/install.sh)
exec "$node" "$cli" "\$@"
LAUNCHER
  chmod 755 "$dir/bin/alran"
  local installed
  installed="$("$dir/bin/alran" --version 2>/dev/null || true)"
  step "Installed Alran Code ${B}${installed:-$version}${N}"

  # ---- PATH ----
  local bin="$dir/bin" rc="" line=""
  case ":$PATH:" in *":$bin:"*) ALRAN_NO_MODIFY_PATH=${ALRAN_NO_MODIFY_PATH:-1} ;; esac
  if [ -z "${ALRAN_NO_MODIFY_PATH:-}" ]; then
    case "$(basename "${SHELL:-sh}")" in
      zsh) rc="${ZDOTDIR:-$HOME}/.zshrc"; line="export PATH=\"$bin:\$PATH\"" ;;
      bash)
        for f in "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.profile"; do [ -f "$f" ] && { rc="$f"; break; }; done
        rc="${rc:-$HOME/.bashrc}"; line="export PATH=\"$bin:\$PATH\"" ;;
      fish) rc="$HOME/.config/fish/config.fish"; line="fish_add_path -g \"$bin\"" ;;
      *) rc="$HOME/.profile"; line="export PATH=\"$bin:\$PATH\"" ;;
    esac
    if ! grep -qsF "$bin" "$rc"; then
      mkdir -p "$(dirname "$rc")"
      printf '\n# Alran Code CLI\n%s\n' "$line" >>"$rc"
      step "Added ${D}$bin${N} to your PATH in ${D}$rc${N}"
    fi
  fi

  say ""
  say "  ${G}✓${N} ${B}Alran Code is ready.${N}"
  say ""
  if [ -n "$rc" ]; then
    say "  Open a new terminal (or run ${B}source $rc${N}), then:"
  else
    say "  Next:"
  fi
  say ""
  say "    ${V}alran auth login${N}     ${D}# sign in with your Ottili account${N}"
  say "    ${V}alran${N}                ${D}# start in your project folder${N}"
  say ""
  say "  ${D}Docs: https://alran.dev/en/docs${N}"
  say ""
}

main "$@"
