#!/usr/bin/env sh
# KCode installer — curl | sh
#
# Detects OS + arch, downloads the right pre-built binary from
# kulvex.ai, installs it to the first writable $PATH entry, and
# verifies the install.
#
# Usage:
#   curl -fsSL https://kulvex.ai/install.sh | sh
#
# Override destination or version:
#   KCODE_INSTALL_DIR=~/bin   sh install.sh
#   KCODE_VERSION=2.10.139    sh install.sh
#
# All the script does is: figure out which binary, wget/curl it,
# chmod +x, move into place. No telemetry, no shell-config edits,
# no sudo prompts unless you point KCODE_INSTALL_DIR at a dir only
# root can write.

set -eu

# ─── Colors (disabled when stderr is not a TTY) ────────────────
if [ -t 2 ]; then
  C_GREEN=$(printf '\033[32m')
  C_CYAN=$(printf '\033[36m')
  C_RED=$(printf '\033[31m')
  C_DIM=$(printf '\033[2m')
  C_BOLD=$(printf '\033[1m')
  C_RESET=$(printf '\033[0m')
else
  C_GREEN=""; C_CYAN=""; C_RED=""; C_DIM=""; C_BOLD=""; C_RESET=""
fi

info()  { printf "%s%s%s\n" "$C_CYAN" "$1" "$C_RESET" >&2; }
ok()    { printf "%s✓%s %s\n" "$C_GREEN" "$C_RESET" "$1" >&2; }
warn()  { printf "%s!%s %s\n" "$C_DIM" "$C_RESET" "$1" >&2; }
fail()  { printf "%s✗%s %s\n" "$C_RED"   "$C_RESET" "$1" >&2; exit 1; }

# ─── Detect OS + arch ─────────────────────────────────────────
uname_s=$(uname -s 2>/dev/null || echo unknown)
uname_m=$(uname -m 2>/dev/null || echo unknown)

case "$uname_s" in
  Linux)        os=linux ;;
  Darwin)       os=macos ;;
  MINGW*|MSYS*|CYGWIN*)
                fail "Windows: please download kcode-*-windows-x64.exe manually from https://kulvex.ai/kcode#downloads" ;;
  *)            fail "Unsupported OS: $uname_s" ;;
esac

case "$uname_m" in
  x86_64|amd64) arch=x64 ;;
  aarch64|arm64)arch=arm64 ;;
  *)            fail "Unsupported architecture: $uname_m" ;;
esac

# Windows binaries come with the .exe suffix; *nix binaries don't.
asset_suffix=""
[ "$os" = "windows" ] && asset_suffix=".exe"

# ─── Resolve version ──────────────────────────────────────────
# If KCODE_VERSION is explicitly set, use it verbatim. Otherwise
# ask kulvex.ai's download index for the newest kcode-X.Y.Z-*
# filename. The listing endpoint is a plain-text file list that's
# regenerated on every release, so parsing it is simple and
# stable — no JSON, no GitHub rate-limits.
version="${KCODE_VERSION:-}"
if [ -z "$version" ]; then
  info "Finding latest version..."
  listing=$(curl -fsSL "https://kulvex.ai/downloads/kcode/" 2>/dev/null || true)
  if [ -z "$listing" ]; then
    fail "Could not reach https://kulvex.ai/downloads/kcode/. Check your network or set KCODE_VERSION explicitly."
  fi
  # Pull every kcode-X.Y.Z-* basename out of the listing, extract
  # the version triples, sort them semver-style (numeric per-field),
  # keep the last one. Portable — no GNU-specific flags.
  version=$(
    echo "$listing" \
      | tr -s ' ' '\n' \
      | grep -oE 'kcode-[0-9]+\.[0-9]+\.[0-9]+' \
      | sed 's/^kcode-//' \
      | awk -F. '{ printf "%04d.%04d.%04d %s\n", $1, $2, $3, $0 }' \
      | sort -r \
      | head -n 1 \
      | awk '{ print $2 }'
  )
  if [ -z "$version" ]; then
    fail "Could not parse latest version from listing. Set KCODE_VERSION explicitly."
  fi
fi
ok "Target version: $version"

# ─── Pick install dir ─────────────────────────────────────────
# Precedence:
#   1. $KCODE_INSTALL_DIR if exported
#   2. ~/.local/bin if it exists and is on PATH (or we can add it)
#   3. ~/.bun/bin if it exists (Bun users)
#   4. /usr/local/bin if writable by current user
#   5. otherwise fall back to ~/.local/bin (create if needed)
install_dir="${KCODE_INSTALL_DIR:-}"
if [ -z "$install_dir" ]; then
  if [ -w "$HOME/.local/bin" ] || mkdir -p "$HOME/.local/bin" 2>/dev/null; then
    install_dir="$HOME/.local/bin"
  elif [ -d "$HOME/.bun/bin" ] && [ -w "$HOME/.bun/bin" ]; then
    install_dir="$HOME/.bun/bin"
  elif [ -w "/usr/local/bin" ]; then
    install_dir="/usr/local/bin"
  else
    install_dir="$HOME/.local/bin"
    mkdir -p "$install_dir" || fail "Could not create $install_dir"
  fi
fi
ok "Install directory: $install_dir"

# ─── Download ────────────────────────────────────────────────
asset="kcode-${version}-${os}-${arch}${asset_suffix}"
url="https://kulvex.ai/downloads/kcode/${asset}"
tmp_file=$(mktemp /tmp/kcode-install.XXXXXX)
trap 'rm -f "$tmp_file"' EXIT INT TERM

info "Downloading $asset ..."
if ! curl -fL --progress-bar -o "$tmp_file" "$url"; then
  fail "Download failed: $url"
fi
size=$(wc -c < "$tmp_file" 2>/dev/null || echo "?")
ok "Downloaded $(( size / 1024 / 1024 )) MB"

# ─── Install ────────────────────────────────────────────────
target="$install_dir/kcode"
# The old binary may be in use (another kcode session running).
# Can't overwrite a running executable on Linux (ETXTBSY), but
# renaming out of the way is fine.
if [ -e "$target" ]; then
  mv "$target" "${target}.old" 2>/dev/null || rm -f "$target"
fi
install -m 0755 "$tmp_file" "$target" 2>/dev/null || {
  cp "$tmp_file" "$target"
  chmod 0755 "$target"
}
rm -f "${target}.old" 2>/dev/null || true

# ─── Verify ──────────────────────────────────────────────────
if [ -x "$target" ]; then
  installed_version=$("$target" --version 2>/dev/null || echo "")
  if [ -z "$installed_version" ]; then
    warn "Installed but --version didn't run (likely Termux/bionic — use proot-distro)"
    echo "    See https://kulvex.ai/kcode#install for Android/Termux instructions."
  elif [ "$installed_version" = "$version" ]; then
    ok "KCode $installed_version installed"
  else
    warn "Installed but version reported $installed_version (expected $version)"
  fi
fi

# ─── PATH hint ────────────────────────────────────────────────
case ":$PATH:" in
  *":$install_dir:"*) ;;
  *)
    printf "\n"
    warn "$install_dir is not on your PATH. Add it so you can run 'kcode' directly:"
    printf "\n"
    printf "  %sexport PATH=\"%s:\$PATH\"%s\n" "$C_BOLD" "$install_dir" "$C_RESET"
    printf "\n"
    printf "  Add the above to your ~/.bashrc or ~/.zshrc to make it permanent.\n"
    ;;
esac

# ─── Next steps ──────────────────────────────────────────────
printf "\n"
printf "  %sNext:%s\n" "$C_BOLD" "$C_RESET"
printf "    %skcode setup%s        — pick a cloud provider or download a local model\n" "$C_CYAN" "$C_RESET"
printf "    %skcode audit .%s      — scan the current repo for bugs\n"                  "$C_CYAN" "$C_RESET"
printf "    %skcode auth login astrolexis%s  — activate KCode Pro via browser\n"        "$C_CYAN" "$C_RESET"
printf "\n"
printf "  %sDocs:%s https://kulvex.ai/kcode\n" "$C_DIM" "$C_RESET"
printf "  %sRepo:%s https://github.com/AstrolexisAI/KCode\n" "$C_DIM" "$C_RESET"
printf "\n"
