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

usage() {
  cat <<'EOF'
Usage:
  curl -fsSL https://aegis.agentic-in.ai/install.sh | bash
  bash install.sh [install|upgrade|health] [options]

Options:
  --install-root PATH   Durable install root. Default: $HOME/.aegis
  --bin-dir PATH        Directory that will receive the aegis launcher. Default: $HOME/.local/bin
  --python PATH         Python interpreter to use. Default: python3
  --channel CHANNEL     Package channel to install. One of: dev, stable. Default: dev
  --pip-spec SPEC       Explicit pip-installable package spec. Overrides --channel
  --skip-run            Skip the automatic aegis launch after install or upgrade
  --skip-health         Deprecated alias for --skip-run
  --help                Show this help text

Environment overrides:
  AEGIS_INSTALL_CHANNEL
  AEGIS_PIP_SPEC
  AEGIS_PYTHON
EOF
}

command_name="install"
install_root="${HOME}/.aegis"
bin_dir="${HOME}/.local/bin"
python_bin="${AEGIS_PYTHON:-python3}"
channel="${AEGIS_INSTALL_CHANNEL:-dev}"
pip_spec="${AEGIS_PIP_SPEC:-}"
package_name="aegis-ag"
skip_run="0"

while [ "$#" -gt 0 ]; do
  case "$1" in
    install|upgrade|health)
      command_name="$1"
      shift
      ;;
    --install-root)
      install_root="$2"
      shift 2
      ;;
    --bin-dir)
      bin_dir="$2"
      shift 2
      ;;
    --python)
      python_bin="$2"
      shift 2
      ;;
    --channel)
      channel="$2"
      shift 2
      ;;
    --pip-spec|--package-source)
      pip_spec="$2"
      shift 2
      ;;
    --skip-run|--skip-health)
      skip_run="1"
      shift
      ;;
    --help|-h)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
done

venv_dir="${install_root}/venv"
venv_python="${venv_dir}/bin/python"
state_dir="${install_root}/state"
gateway_state_dir="${state_dir}/gateway"
profile_dir="${install_root}/profile"
launcher_path="${bin_dir}/aegis"
profile_manifest_path="${profile_dir}/profile.json"

require_command() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "Missing required command: $1" >&2
    exit 1
  fi
}

require_python_version() {
  if ! "$python_bin" - <<'PY'
import sys
sys.exit(0 if sys.version_info >= (3, 12) else 1)
PY
  then
    echo "Aegis currently requires Python 3.12 or newer." >&2
    exit 1
  fi
}

normalize_channel() {
  case "$channel" in
    dev|stable)
      ;;
    *)
      echo "Unsupported channel: $channel" >&2
      exit 2
      ;;
  esac
}

describe_package_selection() {
  if [ -n "${pip_spec}" ]; then
    printf '%s\n' "${pip_spec}"
    return
  fi

  case "${channel}" in
    dev)
      printf '%s\n' "${package_name} (--pre, latest development release)"
      ;;
    stable)
      printf '%s\n' "${package_name} (latest stable release)"
      ;;
  esac
}

ensure_profile_files() {
  mkdir -p "${profile_dir}"
  if [ ! -f "${profile_manifest_path}" ]; then
    cat > "${profile_manifest_path}" <<'EOF'
{
  "profile_id": "profile-local",
  "display_name": "Local Operator",
  "mode": "default",
  "preferences": [
    "tone:precise",
    "memory:durable"
  ],
  "enabled_capabilities": [
    "cli.primary"
  ]
}
EOF
  fi
}

ensure_runtime() {
  mkdir -p "${install_root}"
  if [ ! -x "${venv_python}" ]; then
    "${python_bin}" -m venv "${venv_dir}"
  fi

  "${venv_python}" -m pip install --upgrade pip setuptools wheel >/dev/null
  if [ -n "${pip_spec}" ]; then
    "${venv_python}" -m pip install --upgrade "${pip_spec}"
    return
  fi

  case "${channel}" in
    dev)
      "${venv_python}" -m pip install --upgrade --pre "${package_name}"
      ;;
    stable)
      "${venv_python}" -m pip install --upgrade "${package_name}"
      ;;
  esac
}

write_launcher() {
  mkdir -p "${bin_dir}"
  cat > "${launcher_path}" <<EOF
#!/usr/bin/env bash
set -euo pipefail
install_root="\${AEGIS_HOME:-${install_root}}"
state_dir="\${AEGIS_STATE_DIR:-${state_dir}}"
gateway_state_dir="\${AEGIS_GATEWAY_STATE_DIR:-${gateway_state_dir}}"
profile_dir="\${AEGIS_PROFILE_DIR:-${profile_dir}}"
venv_python="\${AEGIS_PYTHON:-${venv_python}}"

if [ ! -x "\${venv_python}" ]; then
  echo "Aegis runtime is missing: \${venv_python}" >&2
  echo "Run the installer again." >&2
  exit 1
fi

export AEGIS_HOME="\${install_root}"
export AEGIS_STATE_DIR="\${state_dir}"
export AEGIS_GATEWAY_STATE_DIR="\${gateway_state_dir}"
export AEGIS_PROFILE_DIR="\${profile_dir}"
exec "\${venv_python}" -m apps.launcher "\$@"
EOF
  chmod +x "${launcher_path}"
}

run_health() {
  if [ ! -x "${launcher_path}" ]; then
    echo "Launcher not found: ${launcher_path}" >&2
    echo "Run 'curl -fsSL https://aegis.agentic-in.ai/install.sh | bash' first." >&2
    exit 1
  fi
  "${launcher_path}" status
}

run_launcher() {
  if [ ! -x "${launcher_path}" ]; then
    echo "Launcher not found: ${launcher_path}" >&2
    echo "Run 'curl -fsSL https://aegis.agentic-in.ai/install.sh | bash' first." >&2
    exit 1
  fi
  "${launcher_path}"
}

install_or_upgrade() {
  require_command "${python_bin}"
  require_python_version
  normalize_channel
  mkdir -p "${install_root}" "${state_dir}" "${gateway_state_dir}" "${profile_dir}"
  ensure_runtime
  ensure_profile_files
  write_launcher

  echo "Installed Aegis CLI launcher"
  echo "  package: $(describe_package_selection)"
  echo "  install_root: ${install_root}"
  echo "  state_dir: ${state_dir}"
  echo "  gateway_state_dir: ${gateway_state_dir}"
  echo "  profile_dir: ${profile_dir}"
  echo "  runtime: ${venv_python}"
  echo "  launcher: ${launcher_path}"
  if ! printf '%s' ":${PATH}:" | grep -Fq ":${bin_dir}:"; then
    echo "  path_hint: add ${bin_dir} to PATH to call 'aegis' directly"
  fi
  echo "Next commands"
  echo "  - aegis"
  echo "  - aegis init"
  echo "  - aegis status"
  echo "  - aegis wake"
  echo "  - aegis clone nova"

  if [ "${skip_run}" != "1" ]; then
    echo
    echo "Launching Aegis"
    run_launcher
  fi
}

case "${command_name}" in
  install|upgrade)
    install_or_upgrade
    ;;
  health)
    run_health
    ;;
  *)
    echo "Unsupported command: ${command_name}" >&2
    exit 2
    ;;
esac
