#!/bin/sh
# ===========================================================================
#  AkiQai / ProximAgent node installer  (value-free DEVNET)
#  Fetched from get.proximagent.com (full) or get.akiqai.com (node).
#  Test identity + test tokens only. No real value, custody, or launch claim.
# ===========================================================================
set -e

PROFILE="node"
VERSION_STR="0.1.0-devnet"
RAD_RID_DEFAULT=""
RAD_SEED_DEFAULT="https://seed.radicle.garden"
REPO_DEFAULT="https://github.com/ProximAgent/ProximAgent.git"
REF_DEFAULT="main"
PROOF_CID_DEFAULT="bafybeic3j4zav3uadark5mdsr2nciqk2ui3cfd542avpmz4fxxx5mezmey"

c_info() { echo "[akiqai] $1"; }
c_warn() { echo "[akiqai] WARN: $1" 1>&2; }
c_err()  { echo "[akiqai] ERROR: $1" 1>&2; }

banner() {
  echo "=============================================================="
  echo "  AkiQai node installer  -  value-free DEVNET"
  echo "  Test identity + test tokens only. No real value or custody."
  echo "=============================================================="
}

show_help() {
  echo "AkiQai / ProximAgent node installer ($VERSION_STR)"
  echo ""
  echo "Usage:  curl -fsSL https://get.proximagent.com | sh"
  echo "        curl -fsSL https://get.akiqai.com | sh"
  echo "        curl -fsSL https://get.akiqai.com | sh -s -- [options]"
  echo ""
  echo "Profiles (default set by the host you fetched from):"
  echo "  full   agent identity+wallet+inbox, free LLM (llm.proximagent.com),"
  echo "         AND a chain node (pin + witness on; validator gated)"
  echo "  node   an AkiQai chain node first (pin + witness/observer;"
  echo "         validator gated); the agent + LLM are opt-in"
  echo ""
  echo "Options:"
  echo "  --profile full|node   override the default profile"
  echo "  --pin / --no-pin      contribute durable proof storage (AQ-30)"
  echo "  --witness/--no-witness verify L1 checkpoints (observer.akiqai.com)"
  echo "  --agent               also run the ProximAgent agent + its free LLM"
  echo "  --llm / --no-llm      wire the ProximAgent LLM gateway"
  echo "  --llm-key <key>       bring-your-own LLM key instead of the free gateway"
  echo "  --flavor <name>       agent flavor (akiqai|claude|opencode|codex|copilot|custom)"
  echo "  --dir <path>          install dir (default: \$HOME/.akiqai-node)"
  echo "  --ui-port <n>         local dashboard port (default 4177)"
  echo "  --dry-run             print the plan and exit (installs nothing)"
  echo "  --no-run              set up but do not launch"
  echo "  --yes                 allow soft-install of a sandbox backend (brew nono)"
  echo "  --version             print version and exit"
  echo "  -h, --help            this help"
}

# ---- defaults (per profile) ----------------------------------------------
DRY_RUN=0
ASSUME_YES=0
DO_RUN=1
TARGET="$HOME/.akiqai-node"
FLAVOR="akiqai"
LLM_KEY=""
UI_PORT=4177
case "$PROFILE" in
  full) PIN=1; WITNESS=1; LLM=1 ;;
  node) PIN=1; WITNESS=1; LLM=0 ;;
  *)    PIN=1; WITNESS=1; LLM=0; PROFILE=node ;;
esac

# ---- args ----------------------------------------------------------------
while [ $# -gt 0 ]; do
  case "$1" in
    --profile)
      PROFILE="$2"; shift 2
      case "$PROFILE" in
        full) LLM=1 ;;
        node) LLM=0 ;;
        *) c_err "unknown profile: $PROFILE (full|node)"; exit 2 ;;
      esac ;;
    --dry-run) DRY_RUN=1; shift ;;
    --yes|-y) ASSUME_YES=1; shift ;;
    --no-run) DO_RUN=0; shift ;;
    --dir) TARGET="$2"; shift 2 ;;
    --pin) PIN=1; shift ;;
    --no-pin) PIN=0; shift ;;
    --witness) WITNESS=1; shift ;;
    --no-witness) WITNESS=0; shift ;;
    --agent) LLM=1; shift ;;
    --llm) LLM=1; shift ;;
    --no-llm) LLM=0; shift ;;
    --llm-key) LLM=1; LLM_KEY="$2"; shift 2 ;;
    --flavor) FLAVOR="$2"; shift 2 ;;
    --ui-port) UI_PORT="$2"; shift 2 ;;
    -h|--help) show_help; exit 0 ;;
    --version) echo "$VERSION_STR"; exit 0 ;;
    *) c_err "unknown option: $1 (try --help)"; exit 2 ;;
  esac
done

# ---- env overrides (documented) ------------------------------------------
RAD_RID="$RAD_RID_DEFAULT";   if [ -n "$AKIQAI_RAD_RID" ]; then RAD_RID="$AKIQAI_RAD_RID"; fi
RAD_SEED="$RAD_SEED_DEFAULT"; if [ -n "$AKIQAI_RAD_SEED" ]; then RAD_SEED="$AKIQAI_RAD_SEED"; fi
REPO="$REPO_DEFAULT"; if [ -n "$AKIQAI_REPO" ]; then REPO="$AKIQAI_REPO"; fi
REF="$REF_DEFAULT";   if [ -n "$AKIQAI_REF" ]; then REF="$AKIQAI_REF"; fi

# ---- OS / arch detection -------------------------------------------------
OS_RAW="$(uname -s)"
case "$OS_RAW" in
  Linux) OS=linux ;;
  Darwin) OS=macos ;;
  *) OS=unknown ;;
esac
ARCH_RAW="$(uname -m)"
case "$ARCH_RAW" in
  x86_64|amd64) ARCH=amd64 ;;
  aarch64|arm64) ARCH=arm64 ;;
  *) ARCH="$ARCH_RAW" ;;
esac

# ---- sandbox backend detection (nono -> OpenShell -> docker/podman) ------
detect_backend() {
  if command -v nono >/dev/null 2>&1; then echo nono; return 0; fi
  if command -v openshell >/dev/null 2>&1; then echo openshell; return 0; fi
  if command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1; then echo docker; return 0; fi
  if command -v podman >/dev/null 2>&1 && podman info >/dev/null 2>&1; then echo podman; return 0; fi
  echo ""
}

# Soft-install is OPT-IN only (--yes), never as root, never destructive.
soft_install_backend() {
  if [ "$ASSUME_YES" != 1 ]; then return 1; fi
  if [ "$OS" = macos ] && command -v brew >/dev/null 2>&1; then
    c_info "attempting: brew install nono"
    if brew install nono; then return 0; fi
  fi
  return 1
}

guide_backend() {
  c_warn "No sandbox backend found (need nono, OpenShell, Docker, or Podman)."
  echo "  Install ONE of these, then re-run this installer:" 1>&2
  if [ "$OS" = macos ]; then
    echo "    - Docker Desktop:  https://www.docker.com/products/docker-desktop/" 1>&2
    echo "    - nono (kernel sandbox):  brew install nono" 1>&2
  else
    echo "    - Podman (rootless):  https://podman.io/docs/installation" 1>&2
    echo "    - Docker Engine:  https://docs.docker.com/engine/install/" 1>&2
    echo "    - gVisor (runsc) for the strongest isolation:  https://gvisor.dev/docs/user_guide/install/" 1>&2
  fi
}

print_manual_steps() {
  echo "  Fetch the runner manually, then launch it:" 1>&2
  echo "    1. rad clone $RAD_RID $TARGET   # Radicle (decentralized), or:" 1>&2
  echo "       git clone $REPO $TARGET" 1>&2
  echo "    2. cd $TARGET/self-host" 1>&2
  echo "    3. ./run-agent.sh --ui" 1>&2
}

# ---- run -----------------------------------------------------------------
banner

if [ "$(id -u)" = 0 ]; then
  c_err "refusing to run as root. Run as your normal user - the agent must NOT have root."
  exit 1
fi

c_info "profile=$PROFILE  os=$OS  arch=$ARCH"

BACKEND="$(detect_backend)"
if [ -z "$BACKEND" ]; then
  if soft_install_backend; then BACKEND="$(detect_backend)"; fi
fi
if [ -z "$BACKEND" ]; then
  guide_backend
  if [ "$DRY_RUN" = 1 ]; then
    c_info "(dry-run) would stop here until a sandbox backend is installed"
  else
    exit 1
  fi
fi

# ---- fetch the self-host runner (Radicle first, git org fallback) --------
RUNNER=""
if [ -d "$TARGET/self-host" ]; then
  c_info "reusing existing runner at $TARGET/self-host"
  RUNNER="$TARGET/self-host"
elif [ "$DRY_RUN" = 1 ]; then
  c_info "(dry-run) would fetch runner: Radicle rad:$RAD_RID first, then git $REPO (ref $REF)"
  RUNNER="$TARGET/self-host"
else
  fetched=0
  # 1) Radicle — decentralized, primary. rad clone if the CLI is present.
  if [ "$fetched" = 0 ] && [ -n "$RAD_RID" ] && command -v rad >/dev/null 2>&1; then
    c_info "fetching runner from Radicle: rad clone $RAD_RID"
    if rad clone "$RAD_RID" "$TARGET" >/dev/null 2>&1; then fetched=1; fi
  fi
  # 2) git fallback — a neutral remote (no personal account); only if configured.
  if [ "$fetched" = 0 ] && [ -n "$REPO" ] && command -v git >/dev/null 2>&1; then
    c_info "falling back to git clone $REPO (ref $REF)"
    if git clone --depth 1 --branch "$REF" "$REPO" "$TARGET" >/dev/null 2>&1; then fetched=1; fi
  fi
  if [ "$fetched" = 1 ]; then
    RUNNER="$TARGET/self-host"
  else
    c_err "could not fetch the runner from Radicle or git."
    c_err "set AKIQAI_RAD_RID (Radicle repo id) or AKIQAI_REPO (git remote), or install manually."
    print_manual_steps
    exit 1
  fi
fi

# ---- assemble run-agent.sh flags -----------------------------------------
LLM_STR=off; if [ "$LLM" = 1 ]; then LLM_STR=on; fi
FLAGS="--ui --ui-port $UI_PORT"
if [ "$WITNESS" = 1 ]; then FLAGS="$FLAGS --witness"; fi
if [ "$PIN" = 1 ]; then FLAGS="$FLAGS --pin"; fi
if [ "$LLM" = 1 ]; then FLAGS="$FLAGS --llm"; fi
if [ -n "$LLM_KEY" ]; then FLAGS="$FLAGS --llm-key $LLM_KEY"; fi
if [ "$FLAVOR" != akiqai ]; then FLAGS="$FLAGS --flavor $FLAVOR"; fi

# The pin role needs the canonical proof CID. Prefer an env override, else the
# value baked by the worker (may be empty -> the pin role prints guidance).
PIN_CID_VAL="$PROOF_CID_DEFAULT"
if [ -n "$PIN_CID" ]; then PIN_CID_VAL="$PIN_CID"; fi
export PIN_CID="$PIN_CID_VAL"

# ---- print the plan (always, before doing anything) ----------------------
echo ""
c_info "Plan:"
echo "    profile   : $PROFILE"
echo "    sandbox   : $BACKEND"
echo "    runner    : $RUNNER/run-agent.sh"
echo "    roles     : agent(always)  pin=$PIN  witness=$WITNESS  validator=GATED"
echo "    llm       : $LLM_STR"
echo "    command   : ./run-agent.sh $FLAGS"
echo ""

if [ "$DRY_RUN" = 1 ]; then
  c_info "dry-run complete - nothing was installed or started."
  exit 0
fi

if [ -z "$RUNNER" ] || [ ! -f "$RUNNER/run-agent.sh" ]; then
  c_err "runner not available at $RUNNER"
  print_manual_steps
  exit 1
fi

if [ "$DO_RUN" != 1 ]; then
  c_info "prepared. To start:  cd $RUNNER && ./run-agent.sh $FLAGS"
  exit 0
fi

c_info "launching:  ./run-agent.sh $FLAGS"
cd "$RUNNER"
if command -v bash >/dev/null 2>&1; then
  exec bash ./run-agent.sh $FLAGS
fi
chmod +x ./run-agent.sh 2>/dev/null || true
exec ./run-agent.sh $FLAGS
