#!/usr/bin/env bash
# Aesop Agentic user installation. Served unchanged by the documentation site.
set -euo pipefail

usage() {
  cat <<'HELP'
Aesop Agentic Setup

Usage: bash install.sh [options]

  --source PATH     Install from a checkout or unpacked source distribution
  --version VALUE   Install a specific PyPI version (default: latest)
  --python PATH     Python 3.11+ interpreter (default: python3)
  --venv PATH       Environment (default: ~/.local/share/aesop-agentic/venv)
  --workspace PATH  Initial archive workspace (default: ~/Aesop)
  --config PATH     Config (default: AESOP_CONFIG or ~/.config/aesop-agentic/config.toml)
  --bin-dir PATH    Command directory (default: ~/.local/bin)
  --help            Show this help

Creates an isolated environment and an aesop command. Existing configuration is
preserved. Does not collect histories, install a service, or change shell files.
HELP
}

fail() { printf 'Aesop Agentic: %s\n' "$*" >&2; exit 1; }

main() {
  local source_path='' version='' python_bin=python3
  local venv_path="$HOME/.local/share/aesop-agentic/venv"
  local workspace="$HOME/Aesop"
  local config_path="${AESOP_CONFIG:-$HOME/.config/aesop-agentic/config.toml}"
  local bin_dir="$HOME/.local/bin"
  while [ "$#" -gt 0 ]; do
    case "$1" in
      --help|-h) usage; return ;;
      --source|--version|--python|--venv|--workspace|--config|--bin-dir)
        [ "$#" -ge 2 ] && [ -n "$2" ] || fail "Missing value for $1."
        case "$1" in
          --source) source_path=$2 ;; --version) version=$2 ;;
          --python) python_bin=$2 ;; --venv) venv_path=$2 ;;
          --workspace) workspace=$2 ;; --config) config_path=$2 ;;
          --bin-dir) bin_dir=$2 ;;
        esac
        shift 2 ;;
      *) fail "Unknown option: $1. Use --help." ;;
    esac
  done
  [ -z "$source_path" ] || [ -z "$version" ] || fail 'Choose --source or --version, not both.'
  command -v "$python_bin" >/dev/null 2>&1 || fail 'Install Python 3.11 or newer, then rerun setup (or pass --python).'
  "$python_bin" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 11) else 1)' || fail 'Python 3.11 or newer is required.'
  python_bin=$(command -v "$python_bin")

  # Resolve options before changing directory, preserving spaces in paths.
  local path_name resolved
  for path_name in venv_path workspace config_path bin_dir; do
    resolved=$("$python_bin" -c 'import os,sys; print(os.path.abspath(os.path.expanduser(sys.argv[1])))' "${!path_name}")
    printf -v "$path_name" '%s' "$resolved"
  done
  local requirement='aesop-agentic'
  if [ -n "$source_path" ]; then
    source_path=$("$python_bin" -c 'import os,sys; print(os.path.abspath(os.path.expanduser(sys.argv[1])))' "$source_path")
    [ -f "$source_path/pyproject.toml" ] || fail '--source must name an Aesop Agentic source directory.'
    "$python_bin" -c 'import sys,tomllib; assert tomllib.load(open(sys.argv[1], "rb"))["project"]["name"] == "aesop-agentic"' "$source_path/pyproject.toml" || fail 'The source directory is not aesop-agentic.'
    requirement=$source_path
  elif [ -n "$version" ]; then
    [[ "$version" =~ ^[0-9][0-9A-Za-z.+!-]*$ ]] || fail 'Invalid version value.'
    requirement="aesop-agentic==$version"
  fi

  local aesop="$venv_path/bin/aesop" command_path="$bin_dir/aesop"
  local marker="$venv_path/.aesop-agentic-installer"
  # Do not replace another environment or command, including a broken symlink.
  if [ -e "$venv_path" ] || [ -L "$venv_path" ]; then
    [ -f "$marker" ] && [ -x "$venv_path/bin/python" ] || fail "Environment already exists and is not managed by this installer: $venv_path. Choose --venv."
  fi
  if [ -e "$command_path" ] || [ -L "$command_path" ]; then
    [ -L "$command_path" ] && [ "$(readlink "$command_path")" = "$aesop" ] || fail "Command already exists: $command_path. Choose --bin-dir or use your existing installation."
  fi
  [ ! -d "$config_path" ] || fail "Config path is a directory: $config_path."
  if [ -L "$config_path" ] && [ ! -e "$config_path" ]; then
    fail "Config is a broken symlink: $config_path. Repair it before running setup."
  fi

  printf 'Setting up Aesop Agentic in %s\n' "$venv_path"
  if [ ! -f "$marker" ]; then
    "$python_bin" -m venv "$venv_path"
    printf 'Aesop Agentic managed Python environment\n' > "$marker"
  fi
  "$venv_path/bin/python" -m pip install --upgrade "$requirement"
  "$aesop" --version
  if [ -e "$config_path" ]; then
    printf 'Keeping existing configuration: %s\n' "$config_path"
  else
    mkdir -p "$workspace"
    (cd "$workspace" && "$aesop" --config "$config_path" setup)
    "$aesop" --config "$config_path" preferences --ui browser
    printf 'Created configuration: %s\n' "$config_path"
    printf 'Review the default iCloud backup destination before collecting.\n'
  fi
  mkdir -p "$bin_dir"
  if [ ! -L "$command_path" ]; then
    ln -s "$aesop" "$command_path"
  fi
  printf '\nAesop Agentic is ready. Open the interface:\n  '
  printf '%q ' "$command_path" --config "$config_path" browser
  printf '\n'
  case ":$PATH:" in
    *":$bin_dir:"*) ;;
    *) printf '\nTo use aesop by name in this shell:\n  export PATH=%q:"$PATH"\n' "$bin_dir" ;;
  esac
  printf '\nSetup does not start collection or install a background service.\n'
}

main "$@"
