#!/bin/bash
# Unlimited Luna CLI setup — macOS (also works on Linux)
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
INSTALL_DIR="${HOME}/.unlimited/rt"
LAUNCHER="${HOME}/.unlimited/unlimited"
PKG_URL="${UCX_PKG_URL:-https://unlimitedcodex.com/downloads/unlimited-cli-package.zip?v=luna-20260814-v393}"
export PYTHONIOENCODING=utf-8
export PYTHONUTF8=1
PKG_ZIP="${TMPDIR:-/tmp}/unlimited-cli-package.zip"

echo ""
echo "=================================================="
echo " Unlimited Luna CLI setup"
echo " unlimitedcodex.com"
echo "=================================================="
echo ""
echo "Tip: place unlimited-cli-package.zip next to this script for offline install."
echo ""

if ! command -v python3 >/dev/null 2>&1; then
  echo "[ERROR] Python 3 not found. Install Python 3.9+ and re-run."
  exit 1
fi
PY=python3
echo "[1/5] Python: $($PY --version)"

echo "[2/5] Package..."
if [ -n "${UCX_LOCAL_ZIP:-}" ] && [ -f "$UCX_LOCAL_ZIP" ]; then
  echo "      Local zip (UCX_LOCAL_ZIP): $UCX_LOCAL_ZIP"
  cp -f "$UCX_LOCAL_ZIP" "$PKG_ZIP"
elif [ -f "$SCRIPT_DIR/unlimited-cli-package.zip" ]; then
  echo "      Local zip next to setup"
  cp -f "$SCRIPT_DIR/unlimited-cli-package.zip" "$PKG_ZIP"
else
  echo "      Downloading Luna package..."
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$PKG_URL" -o "$PKG_ZIP"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO "$PKG_ZIP" "$PKG_URL"
  else
    echo "[ERROR] Need curl or wget to download the package."
    exit 1
  fi
fi

echo "[3/5] Install to: $INSTALL_DIR"
rm -rf "$INSTALL_DIR"
mkdir -p "$INSTALL_DIR" "$(dirname "$LAUNCHER")"
if command -v unzip >/dev/null 2>&1; then
  unzip -qo "$PKG_ZIP" -d "$INSTALL_DIR"
else
  $PY -c "import zipfile,sys; zipfile.ZipFile(sys.argv[1]).extractall(sys.argv[2])" "$PKG_ZIP" "$INSTALL_DIR"
fi
if [ ! -f "$INSTALL_DIR/main.py" ]; then
  echo "[ERROR] main.py missing in package"
  exit 1
fi
if [ ! -f "$INSTALL_DIR/rt.ok" ] && [ ! -f "$INSTALL_DIR/.rt" ] && [ ! -d "$INSTALL_DIR/n4k9" ] && [ ! -d "$INSTALL_DIR/luna" ]; then
  echo "[ERROR] Invalid package layout"
  exit 1
fi
# remove legacy install path if present
rm -rf "${HOME}/.unlimited/app" 2>/dev/null || true

echo "[4/5] Dependencies..."
# Strip UTF-8 BOM from pyproject.toml if present (breaks Python 3.11+ tomllib / pip -e).
if [ -f "$INSTALL_DIR/pyproject.toml" ]; then
  $PY -c "from pathlib import Path; p=Path(r'''$INSTALL_DIR''')/'pyproject.toml'; b=p.read_bytes(); p.write_bytes(b[3:] if b.startswith(b'\\xef\\xbb\\xbf') else b)"
fi
$PY -m pip install --user -q -U pip
$PY -m pip install --user -q -r "$INSTALL_DIR/requirements.txt"
$PY -m pip install --user -q -e "$INSTALL_DIR" || true

# Harden: compile + strip readable sources (best-effort)
if [ -f "$INSTALL_DIR/lock_install.py" ]; then
  echo "      Locking install tree..."
  $PY "$INSTALL_DIR/lock_install.py" "$INSTALL_DIR" >/dev/null 2>&1 || true
fi

cat > "$LAUNCHER" <<EOF
#!/bin/bash
export PYTHONIOENCODING=utf-8
export PYTHONUTF8=1
exec $PY "$INSTALL_DIR/main.py" "\$@"
EOF
chmod +x "$LAUNCHER"
cp -f "$LAUNCHER" "$SCRIPT_DIR/unlimited" 2>/dev/null || true
# Also place on PATH-friendly name without extension
cp -f "$LAUNCHER" "${HOME}/.unlimited/unlimited" 2>/dev/null || true
chmod +x "${HOME}/.unlimited/unlimited" 2>/dev/null || true

# Prepend ~/.unlimited to user shell PATH if missing
UCX_BIN="${HOME}/.unlimited"
PATH_LINE="export PATH=\"${UCX_BIN}:\$PATH\""
for rc in "${HOME}/.zshrc" "${HOME}/.bashrc" "${HOME}/.profile"; do
  if [ -f "$rc" ] || [ "$rc" = "${HOME}/.profile" ]; then
    if ! grep -qF '.unlimited' "$rc" 2>/dev/null; then
      echo "" >> "$rc"
      echo "# Unlimited Luna CLI" >> "$rc"
      echo "$PATH_LINE" >> "$rc"
      echo "      PATH updated in $rc (open a new terminal, then: unlimited)"
      break
    fi
  fi
done

echo "[5/5] API key (Enter to skip chat):"
read -r UCX_KEY || true
if [ -z "${UCX_KEY:-}" ]; then
  echo "Install complete without login."
  echo "Later: $LAUNCHER login --key sk-..."
  echo "       $LAUNCHER"
  exit 0
fi

# Single public gateway — no base URL prompt (Unlimited Luna CLI).
UCX_URL="https://api.unlimitedcodex.com"

$PY "$INSTALL_DIR/main.py" login --key "$UCX_KEY" --url "$UCX_URL"
unset UCX_KEY UCX_URL

echo ""
echo "Setup complete. Starting Unlimited Luna CLI..."
echo "Later: $LAUNCHER   or   unlimited"
echo ""
exec $PY "$INSTALL_DIR/main.py"
