#!/usr/bin/env bash
# kuzy install — clones the repo and installs the Kuzy CLI in editable mode
# under $KUZY_HOME (default ~/.kuzy/src).
#
#   curl -fsSL https://kuzy.ai/install.sh | bash
#
# Requirements: git, python3 (3.11+), pip. The script refuses to run as root
# and refuses to overwrite an existing non-git directory.

set -euo pipefail

if [ "$(id -u)" = "0" ]; then
  echo "kuzy install: refuse to run as root. Re-run as your user." >&2
  exit 1
fi

KUZY_HOME="${KUZY_HOME:-$HOME/.kuzy}"
SRC_DIR="$KUZY_HOME/src"
REPO_URL="https://github.com/bulbulogludemir/kuzy.git"

PY="${PYTHON:-python3}"
if ! command -v "$PY" >/dev/null 2>&1; then
  echo "kuzy install: python3 not found in PATH. Install Python 3.11+ first." >&2
  exit 1
fi
if ! command -v git >/dev/null 2>&1; then
  echo "kuzy install: git not found in PATH. Install git first." >&2
  exit 1
fi

PY_VER="$("$PY" -c 'import sys; print("%d.%d" % sys.version_info[:2])')"
if ! "$PY" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 11) else 1)'; then
  echo "kuzy install: Python 3.11+ required (found ${PY_VER})." >&2
  exit 1
fi

mkdir -p "$KUZY_HOME"

if [ -e "$SRC_DIR" ] && [ ! -d "$SRC_DIR/.git" ]; then
  echo "kuzy install: $SRC_DIR exists but isn't a git checkout. Move it aside first." >&2
  exit 1
fi

if [ -d "$SRC_DIR/.git" ]; then
  echo "==> Updating existing checkout in $SRC_DIR"
  git -C "$SRC_DIR" fetch --tags --prune
  git -C "$SRC_DIR" pull --ff-only
else
  echo "==> Cloning $REPO_URL into $SRC_DIR"
  git clone --depth 50 "$REPO_URL" "$SRC_DIR"
fi

echo "==> Installing Python package (editable, --user)"
"$PY" -m pip install --user --upgrade pip >/dev/null
"$PY" -m pip install --user -e "$SRC_DIR"

KUZY_LAUNCHER="$SRC_DIR/kuzy"
HENRY_LAUNCHER="$SRC_DIR/henry"
chmod +x "$KUZY_LAUNCHER" "$HENRY_LAUNCHER" 2>/dev/null || true

USER_BIN="$HOME/.local/bin"
mkdir -p "$USER_BIN"
ln -sf "$KUZY_LAUNCHER" "$USER_BIN/kuzy"
ln -sf "$HENRY_LAUNCHER" "$USER_BIN/henry"

cat <<EOF

Installed to: $SRC_DIR
Launcher:     $USER_BIN/kuzy  ($USER_BIN/henry remains as a legacy alias)

If '$USER_BIN' is not on your PATH, add it:
  export PATH="\$HOME/.local/bin:\$PATH"

Then run:
  kuzy --cli             # plain Rich CLI
  kuzy                   # Ink terminal UI (needs Bun)
  kuzy onboarding        # first-run provider + auth setup

Docs: https://kuzy.ai/docs/cli
Source: $REPO_URL
EOF
