#!/usr/bin/env bash
# install-aria-cli.sh — Aria CLI installer (Sprint 020 R3.T1-A v0.1 minimum).
#
# Usage (from the /onboarding/install-aria-cli page):
#   curl -fsSL https://staycool.ai/install/aria-cli | bash -s -- <ENROLL_TOKEN>
#
# What it does:
#   1. Validates the enroll_token (non-empty)
#   2. Picks an install directory (~/.aria-cli/)
#   3. Downloads the aria-cli Python script
#   4. Detects platform + hostname
#   5. Calls POST /aria-cli/enroll exchanging enroll_token → auth_token
#   6. Stores ~/.aria-cli/config (auth_token + device_id + server URL)
#   7. Adds an alias / PATH shim
#   8. Prints next steps + the systemd-user / launchd template
#
# v0.1 scope: this is install + enroll only. The daemon side ships as a
# user-runnable command (aria-cli pull) — proper background daemon is post-launch.

set -euo pipefail

SERVER="${ARIA_SERVER:-https://staycool.ai}"
ENROLL_TOKEN="${1:-}"
INSTALL_DIR="${HOME}/.aria-cli"
CLI_FILE="${INSTALL_DIR}/aria-cli"
CONFIG_FILE="${INSTALL_DIR}/config"

err() { printf '\033[31m✗ %s\033[0m\n' "$*" >&2; }
ok()  { printf '\033[32m✓ %s\033[0m\n' "$*"; }
say() { printf '  %s\n' "$*"; }

if [[ -z "${ENROLL_TOKEN}" ]]; then
  err "Missing ENROLL_TOKEN."
  say "Run via: curl -fsSL ${SERVER}/install/aria-cli | bash -s -- <ENROLL_TOKEN>"
  say "Get a token by signing in at ${SERVER}/onboarding/install-aria-cli"
  exit 2
fi

# Platform detection
case "$(uname -s)" in
  Darwin) PLATFORM="macos"   ;;
  Linux)  PLATFORM="linux"   ;;
  *)      PLATFORM="other"   ;;
esac
HOSTNAME_DETECTED="$(hostname -s 2>/dev/null || hostname || echo 'unknown')"

# Need python3 + curl
if ! command -v python3 >/dev/null; then
  err "python3 not found in PATH. Install Python 3.8+ first."
  exit 3
fi
if ! command -v curl >/dev/null; then
  err "curl not found in PATH."
  exit 3
fi

mkdir -p "${INSTALL_DIR}"
chmod 700 "${INSTALL_DIR}"

ok "Downloading aria-cli to ${CLI_FILE}…"
curl -fsSL "${SERVER}/static/aria-cli.py" -o "${CLI_FILE}"
chmod 755 "${CLI_FILE}"

ok "Enrolling device with ${SERVER}…"
ENROLL_RESP="$(curl -fsS -X POST "${SERVER}/aria-cli/enroll" \
  -H 'Content-Type: application/json' \
  -d "$(python3 -c "import json,sys; print(json.dumps({'enroll_token': sys.argv[1], 'hostname': sys.argv[2], 'platform': sys.argv[3]}))" "${ENROLL_TOKEN}" "${HOSTNAME_DETECTED}" "${PLATFORM}")")"

# Extract device_id + auth_token without depending on jq
DEVICE_ID="$(python3 -c 'import json,sys; print(json.loads(sys.argv[1])["device_id"])' "${ENROLL_RESP}")"
AUTH_TOKEN="$(python3 -c 'import json,sys; print(json.loads(sys.argv[1])["auth_token"])' "${ENROLL_RESP}")"
USER_EMAIL="$(python3 -c 'import json,sys; print(json.loads(sys.argv[1])["user_email"])' "${ENROLL_RESP}")"

# Persist config (mode 600)
umask 077
cat > "${CONFIG_FILE}" <<EOF
# Aria CLI config — created $(date -u +%Y-%m-%dT%H:%M:%SZ)
# DO NOT commit or share this file. It contains a long-lived device auth token.
ARIA_SERVER=${SERVER}
ARIA_DEVICE_ID=${DEVICE_ID}
ARIA_AUTH_TOKEN=${AUTH_TOKEN}
ARIA_USER_EMAIL=${USER_EMAIL}
EOF
chmod 600 "${CONFIG_FILE}"

ok "Enrolled as device ${DEVICE_ID} (user: ${USER_EMAIL})"

# Best-effort PATH shim — print but don't force
SHIM_LINE="alias aria-cli='${CLI_FILE}'"
say ""
say "─────────────────────────────────────────"
ok "aria-cli installed. Add to your shell:"
say ""
say "  echo \"${SHIM_LINE}\" >> ~/.zshrc   # or ~/.bashrc"
say "  source ~/.zshrc"
say ""
ok "Then test with:"
say ""
say "  aria-cli pull        # poll once for jobs"
say "  aria-cli devices     # list your devices on the server"
say ""
ok "To run aria-cli on a schedule (recommended every 60s):"
case "${PLATFORM}" in
  macos)
    say "  # launchd template — adapt to your needs:"
    say "  cat > ~/Library/LaunchAgents/io.ariacode.cli.plist <<PLIST"
    say "  <plist version=\"1.0\"><dict>"
    say "    <key>Label</key><string>io.ariacode.cli</string>"
    say "    <key>ProgramArguments</key>"
    say "    <array><string>${CLI_FILE}</string><string>pull</string></array>"
    say "    <key>StartInterval</key><integer>60</integer>"
    say "  </dict></plist>"
    say "  PLIST"
    say "  launchctl load ~/Library/LaunchAgents/io.ariacode.cli.plist"
    ;;
  linux)
    say "  # systemd --user template — adapt:"
    say "  mkdir -p ~/.config/systemd/user"
    say "  cat > ~/.config/systemd/user/aria-cli.timer <<UNIT"
    say "  [Unit]"
    say "  Description=Aria CLI poll"
    say "  [Timer]"
    say "  OnBootSec=30s"
    say "  OnUnitActiveSec=60s"
    say "  [Install]"
    say "  WantedBy=timers.target"
    say "  UNIT"
    say "  # plus matching .service file → ExecStart=${CLI_FILE} pull"
    say "  systemctl --user enable --now aria-cli.timer"
    ;;
  *)
    say "  # cron one-liner for everything else:"
    say "  ( crontab -l 2>/dev/null; echo '* * * * * ${CLI_FILE} pull >/dev/null 2>&1' ) | crontab -"
    ;;
esac
say ""
ok "Done."
