#!/usr/bin/env bash
set -euo pipefail

# Agentify CLI installer
# Usage:
#   curl -fsSL https://install.agentify.sh | bash
#   curl -fsSL https://cli.agentify.sh/install.sh | bash

AGENTIFY_HOME="${AGENTIFY_HOME:-$HOME/.agentify}"
AGENTIFY_BIN_DIR="$AGENTIFY_HOME/bin"
AGENTIFY_VENV="$AGENTIFY_HOME/venv"
AGENTIFY_SHIM="$AGENTIFY_BIN_DIR/agentify"
AGENTIFY_PIP_PACKAGE="${AGENTIFY_PIP_PACKAGE:-agentify-cli}"
AGENTIFY_SOURCE_URL="${AGENTIFY_SOURCE_URL:-https://install.agentify.sh/agentify-cli-src.tar.gz}"
AGENTIFY_GIT_URL="${AGENTIFY_GIT_URL:-https://github.com/waml/crowd4gpt.com.git}"
AGENTIFY_GIT_SUBDIR="${AGENTIFY_GIT_SUBDIR:-cli}"

log() { printf '%s\n' "$*"; }
warn() { printf 'WARN: %s\n' "$*" >&2; }
err() { printf 'ERROR: %s\n' "$*" >&2; }

platform="$(uname -s 2>/dev/null || true)"
case "$platform" in
  Darwin|Linux) ;;
  *)
    warn "Unsupported platform: ${platform:-unknown}. Use macOS, Linux, or Windows WSL."
    ;;
esac

if [[ "$platform" == "Linux" ]] && [[ -r /proc/version ]] && grep -qi "microsoft" /proc/version; then
  log "Detected WSL environment."
fi

need_cmd() {
  command -v "$1" >/dev/null 2>&1
}

choose_python() {
  if need_cmd python3; then
    printf 'python3'
    return 0
  fi
  if need_cmd python; then
    printf 'python'
    return 0
  fi
  return 1
}

python_cmd="$(choose_python || true)"
if [[ -z "${python_cmd:-}" ]]; then
  err "Python 3.10+ is required."
  exit 1
fi

if ! "$python_cmd" - <<'PY' >/dev/null 2>&1
import sys
raise SystemExit(0 if sys.version_info >= (3, 10) else 1)
PY
then
  err "Python 3.10+ is required."
  exit 1
fi

mkdir -p "$AGENTIFY_BIN_DIR"

if [[ ! -d "$AGENTIFY_VENV" ]]; then
  log "Creating virtualenv at $AGENTIFY_VENV"
  "$python_cmd" -m venv "$AGENTIFY_VENV"
fi

PIP="$AGENTIFY_VENV/bin/pip"
PY="$AGENTIFY_VENV/bin/python"
CLI_BIN="$AGENTIFY_VENV/bin/agentify"

log "Upgrading pip/setuptools/wheel"
"$PY" -m pip install --upgrade pip setuptools wheel >/dev/null

install_from_pypi() {
  log "Installing $AGENTIFY_PIP_PACKAGE from package index"
  "$PIP" install --upgrade "$AGENTIFY_PIP_PACKAGE"
}

install_from_source_bundle() {
  if ! need_cmd curl; then
    warn "curl is not installed; cannot fetch source bundle."
    return 1
  fi
  if ! need_cmd tar; then
    warn "tar is not installed; cannot extract source bundle."
    return 1
  fi
  local tmp archive src
  tmp="$(mktemp -d "${AGENTIFY_HOME}/tmp.bundle.XXXXXX")"
  archive="$tmp/agentify-cli-src.tar.gz"
  src="$tmp/src"
  log "Falling back to source bundle from $AGENTIFY_SOURCE_URL"
  if ! curl -fsSL "$AGENTIFY_SOURCE_URL" -o "$archive"; then
    warn "source bundle download failed from $AGENTIFY_SOURCE_URL"
    return 1
  fi
  mkdir -p "$src"
  if ! tar -xzf "$archive" -C "$src"; then
    warn "source bundle extraction failed"
    return 1
  fi
  if [[ ! -f "$src/pyproject.toml" ]] || [[ ! -d "$src/agentify_cli" ]]; then
    warn "source bundle contents are incomplete"
    return 1
  fi
  "$PIP" install --upgrade "$src"
  log "Temporary source bundle left at $tmp for inspection."
}

install_from_git() {
  if ! need_cmd git; then
    warn "git is not installed; cannot fallback to source install."
    return 1
  fi
  local tmp
  tmp="$(mktemp -d "${AGENTIFY_HOME}/tmp.install.XXXXXX")"
  log "Falling back to source install from $AGENTIFY_GIT_URL ($AGENTIFY_GIT_SUBDIR)"
  if ! git clone --depth 1 "$AGENTIFY_GIT_URL" "$tmp/repo" >/dev/null 2>&1; then
    warn "git clone failed for $AGENTIFY_GIT_URL"
    return 1
  fi
  if [[ ! -d "$tmp/repo/$AGENTIFY_GIT_SUBDIR" ]]; then
    warn "source checkout does not contain subdir: $AGENTIFY_GIT_SUBDIR"
    return 1
  fi
  "$PIP" install --upgrade "$tmp/repo/$AGENTIFY_GIT_SUBDIR"
  log "Temporary source checkout left at $tmp for inspection."
}

if ! install_from_pypi; then
  warn "Package index install failed."
  if ! install_from_source_bundle; then
    warn "Source bundle install failed."
    if ! install_from_git; then
      err "Install failed from package index, source bundle, and source fallback."
      err "If this is a private beta, run the manual fallback from cli.agentify.sh/cli."
      exit 1
    fi
  fi
fi

cat >"$AGENTIFY_SHIM" <<EOF
#!/usr/bin/env bash
exec "$CLI_BIN" "\$@"
EOF
chmod +x "$AGENTIFY_SHIM"

if [[ ! -x "$CLI_BIN" ]]; then
  err "Install finished without producing $CLI_BIN"
  exit 1
fi

if [[ ":$PATH:" != *":$AGENTIFY_BIN_DIR:"* ]]; then
  warn "$AGENTIFY_BIN_DIR is not in your PATH."
  warn "Add this to your shell profile:"
  warn "  export PATH=\"$AGENTIFY_BIN_DIR:\$PATH\""
fi

log "Installed Agentify CLI."
"$CLI_BIN" --help >/dev/null
log "Run:"
log "  agentify start"
