#!/bin/sh
# This script installs SmartDecision on Linux.
#
# SmartDecision runs as two containers managed by docker compose:
#   smartdecision      the app (always; tens of MB of RAM)
#   smartdecision-llm  the built-in AI (optional): the public llama-swap image,
#                      which runs llama.cpp's llama-server only while decisions
#                      are being authored and unloads it after 10 min idle
# Instead of the built-in AI, the app can use your own AI server on your
# network (Ollama, vLLM or llama.cpp's llama-server).
#
# Usage: install.sh [--llm=builtin|external|none]
#                   [--llm-url=URL] [--llm-model=NAME] [--llm-api-key=KEY]
#                   [--key=KEY] [--license=KEY] [--version=VERSION] [--url=URL]
#                   [--setup-token=TOKEN]
# Without --llm, the script asks; without a license key too.
# The license key is the only credential: the app image and the model weights
# come from the download portal (get.smartdecision.io), which checks the key.
# The app image arrives as a `docker save` tarball and is loaded with
# `docker load`, so there is no registry to log into.
# Its checksums are signed with Wingravity's release key, checked with
# openssl (3.0 or later) before anything is loaded.
#   --key       downloads with this key; it is kept in .env for later runs.
#   --license   same, and also locks it in the app as SMARTDECISION_LICENSE
#               (unattended installs); otherwise the app installs the key on
#               its first start and an admin can replace it in Settings.
#   --version   installs that version instead of the newest one the key covers.
#   --url       the address apps and teammates use to reach SmartDecision, e.g.
#               https://decisions.example.com; it shows up in "Use in app" and
#               in invitation links. Default: this server's IP on port 8080.
#               Admins can change it in Settings.
#   --setup-token  protects the first sign-up: only the link
#               <address>/signup?invitation=TOKEN can create the admin account,
#               from the very first start. At least 16 letters, digits, - _ . ~;
#               kept in .env for later runs. Without it, the first person to
#               sign up becomes the admin.

PORTAL_URL="${SMARTDECISION_PORTAL:-https://get.smartdecision.io}"
APP_IMAGE_NAME="smartdecision"
LLM_CONTAINER_NAME="smartdecision-llm"
# Upstream llama-swap + llama.cpp build (llama-swap v260, llama.cpp b11223),
# pinned by digest; the app's LLM settings were tested against it. Its config
# is written below (LLM_CONFIG_FILE), so no image of our own is needed.
LLM_IMAGE="ghcr.io/mostlygeek/llama-swap:v260-cpu-b11223@sha256:8191baa71e94a58f1a895487363e0c9eb501ae5affab7cb7a8bd00e43f5e440e"

SOURCE_ROOT="$HOME/.smartdecision"
TARGET_ROOT="/bin/smartdecision"

DATABASE_SOURCE="$SOURCE_ROOT/local.db"
IMAGES_SOURCE="$SOURCE_ROOT/images"
LOGS_SOURCE="$SOURCE_ROOT/all.log"
MODELS_SOURCE="$SOURCE_ROOT/models"
COMPOSE_FILE="$SOURCE_ROOT/compose.yaml"
ENV_FILE="$SOURCE_ROOT/.env"
LLM_CONFIG_FILE="$SOURCE_ROOT/llm-config.yaml"

CLI_TARGET="$TARGET_ROOT/cli"

# Pinned model build: the app's prompts and tests are calibrated against these
# exact weights. Update URL, file name and checksum together.
MODEL_FILE="Qwen3-4B-Instruct-2507-Q4_K_M.gguf"
# Served by the download portal (a copy of unsloth/Qwen3-4B-Instruct-2507-GGUF).
MODEL_URL="$PORTAL_URL/v1/shared/models/$MODEL_FILE"
MODEL_SHA256="3605803b982cb64aead44f6c1b2ae36e3acdb41d8e46c8a94c6533bc4c67e597"

# Wingravity's release key (Ed25519). Each release's SHA256SUMS is signed with
# it (SHA256SUMS.sig), so an image is only loaded if Wingravity built it, even
# if the download portal were compromised. Same key as releasePublicKey in
# app/cmd/release (`go run ./cmd/release pubkey`); change both together.
RELEASE_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEADHx9LY+SgtlkXsOxfblk4aiW0xFzfrBlE57QkNreLw0=
-----END PUBLIC KEY-----"

LLM_MODE=
LLM_URL=
LLM_MODEL=
LLM_API_KEY=
KEY=
LICENSE=
VERSION=
SERVER_URL=

for arg in "$@"; do
  case $arg in
    --llm=*) LLM_MODE="${arg#*=}" ;;
    --llm-url=*) LLM_URL="${arg#*=}" ;;
    --llm-model=*) LLM_MODEL="${arg#*=}" ;;
    --llm-api-key=*) LLM_API_KEY="${arg#*=}" ;;
    --key=*) KEY="${arg#*=}" ;;
    --license=*) LICENSE="${arg#*=}" ;;
    --version=*) VERSION="${arg#*=}" ;;
    --url=*) SERVER_URL="${arg#*=}" ;;
    --setup-token=*) SETUP_TOKEN="${arg#*=}" ;;
    *) echo "Unknown option: $arg" >&2; exit 1 ;;
  esac
done

case $LLM_MODE in
  ""|builtin|external|none) ;;
  *) echo "Error: --llm must be builtin, external or none." >&2; exit 1 ;;
esac

# Versions end up in file names, URLs and compose.yaml.
valid_version() {
  case $1 in
    ""|*[!0-9A-Za-z.+-]*) return 1 ;;
  esac
}
if [ -n "$VERSION" ] && ! valid_version "$VERSION"; then
  echo "Error: --version must look like 1.4.0." >&2
  exit 1
fi

# The address ends up quoted in .env.
case $SERVER_URL in
  *[!A-Za-z0-9.:/_~%\[\]-]*)
    echo "Error: --url must be an address like https://decisions.example.com." >&2
    exit 1
    ;;
esac

# The setup token ends up quoted in .env and in a link.
if [ -n "$SETUP_TOKEN" ]; then
  case $SETUP_TOKEN in
    *[!A-Za-z0-9._~-]*) bad_token=true ;;
    *) [ ${#SETUP_TOKEN} -lt 16 ] && bad_token=true ;;
  esac
  if [ "$bad_token" = true ]; then
    echo "Error: --setup-token must be at least 16 letters, digits, - _ . or ~." >&2
    exit 1
  fi
fi

case $(uname -m) in
  x86_64|amd64) ARCH=amd64 ;;
  aarch64|arm64) ARCH=arm64 ;;
  *) echo "Error: SmartDecision runs on amd64 and arm64, not $(uname -m)." >&2; exit 1 ;;
esac

# Checking the release signature needs Ed25519 in openssl, which came in 3.0
# (Ubuntu 22.04, Debian 12, RHEL 9 and later ship it).
openssl_major=$(openssl version 2>/dev/null | awk '$1 == "OpenSSL" { split($2, v, "."); print v[1] }')
if [ "${openssl_major:-0}" -lt 3 ]; then
  echo "Error: The installer needs OpenSSL 3 or later to check the release signature." >&2
  echo 'Please install it (package openssl) and try again'
  exit 1
fi

# read -s is a bash-ism; this works in dash (Ubuntu's /bin/sh) too.
read_secret() {
  trap 'stty echo 2>/dev/null; echo; exit 130' INT TERM
  stty -echo 2>/dev/null
  read "$1"
  stty echo 2>/dev/null
  trap - INT TERM
  echo
}

# curl_auth TOKEN CURL_ARGS... sends TOKEN as a Bearer header through a curl
# config on stdin, so it never shows in the process list (ps, /proc).
curl_auth() {
  token=$(printf '%s' "$1" | sed 's/[\\"]/\\&/g')
  shift
  printf 'header = "Authorization: Bearer %s"\n' "$token" | curl -K - "$@"
}

echo "
                      __     __        _     _             _
  ___ __ _  ___ _____/ /____/ /__ ____(_)__ (_)__  ___    (_)__
 (_-</  ' \/ _ \`/ __/ __/ _  / -_) __/ (_-</ / _ \/ _ \_ / / _ \\
/___/_/_/_/\_,_/_/  \__/\_,_/\__/\__/_/___/_/\___/_//_(_)_/\___/
"

# Re-running without --license or --key keeps the keys from an earlier run.
env_value() {
  [ -f $ENV_FILE ] && sed -n "s/^$1='\(.*\)'\$/\1/p" $ENV_FILE
}
if [ -z "$LICENSE" ]; then
  LICENSE=$(env_value SMARTDECISION_LICENSE)
fi
[ -z "$KEY" ] && KEY=$LICENSE
[ -z "$KEY" ] && KEY=$(env_value SMARTDECISION_DOWNLOAD_KEY)
if [ -z "$KEY" ]; then
  printf "\033[1mPaste the license key from your SmartDecision welcome email\033[0m\n"
  printf "License key: "
  read_secret KEY
fi
# Pasted keys often pick up spaces or line breaks.
KEY=$(printf '%s' "$KEY" | tr -d '[:space:]')
LICENSE=$(printf '%s' "$LICENSE" | tr -d '[:space:]')
if [ -z "$KEY" ]; then
  echo "Error: A license key is required to download SmartDecision." >&2
  echo 'It is in your welcome email; the download portal can resend it'
  exit 1
fi
# Keys are base64url and dots; anything else is a paste gone wrong, and would
# break the quoting in .env.
case $KEY$LICENSE in
  *[!A-Za-z0-9._-]*)
    echo "Error: The license key contains characters a key never has." >&2
    echo 'Please copy it again from your welcome email'
    exit 1
    ;;
esac

# portal_get PATH FILE saves a small file from the download portal. On an
# error answer it prints the portal's message and returns 1.
portal_get() {
  code=$(curl_auth "$KEY" -sS -o "$2" -w '%{http_code}' "$PORTAL_URL$1") || return 1
  if [ "$code" != "200" ]; then
    message=$(sed -n 's/.*"message":"\([^"]*\)".*/\1/p' "$2" 2>/dev/null)
    echo "Error: ${message:-The download portal answered HTTP $code.}" >&2
    rm -f "$2"
    return 1
  fi
}

if [ -z "$LLM_MODE" ]; then
  printf "\n\033[1mHow should SmartDecision draft decisions from policy text?\033[0m\n"
  echo "  1) Built-in AI (downloads a 2.5 GB model; needs ~8 GB RAM, only while authoring)"
  echo "  2) My own AI server on my network (Ollama, vLLM, llama.cpp...)"
  echo "  3) No AI (decisions are built from templates or by hand)"
  printf "Choose [1-3, default 1]: "
  read choice
  case $choice in
    ""|1) LLM_MODE=builtin ;;
    2) LLM_MODE=external ;;
    3) LLM_MODE=none ;;
    *) echo "Error: Invalid choice $choice." >&2; exit 1 ;;
  esac
fi

if [ "$LLM_MODE" = "external" ]; then
  if [ -z "$LLM_URL" ]; then
    printf "AI server base URL (e.g. http://gpu-box:11434/v1): "
    read LLM_URL
  fi
  if [ -z "$LLM_MODEL" ]; then
    printf "Model name: "
    read LLM_MODEL
  fi
  if [ -z "$LLM_API_KEY" ]; then
    printf "API key (leave empty if none): "
    read_secret LLM_API_KEY
  fi
  if [ -z "$LLM_URL" ] || [ -z "$LLM_MODEL" ]; then
    echo "Error: Your own AI server needs both a URL and a model name." >&2
    exit 1
  fi
  # These are written to .env inside single quotes.
  NL='
'
  case $LLM_URL$LLM_MODEL$LLM_API_KEY in
    *"'"*|*"$NL"*)
      echo "Error: The AI server URL, model name and API key cannot contain ' or line breaks." >&2
      exit 1
      ;;
  esac
  case $LLM_URL in
    *://localhost|*://localhost[:/]*|*://127.0.0.1*)
      echo "[WARN] $LLM_URL points at the app container itself." >&2
      echo "To reach a server on this host, use host.docker.internal instead of localhost." >&2
      ;;
  esac
fi

SUDO=
if [ "$(id -u)" -ne 0 ]; then
  if ! command -v sudo >/dev/null; then
    echo "Error: This script requires superuser permissions. Please re-run as root."
    exit 1
  fi
  SUDO="sudo"
fi

echo "> Checking the docker installation..."
if ! $SUDO docker --version; then
  echo "Docker is not installed. Installing Docker..." >&2
  # A private directory, so nobody else can swap the script before sudo runs it.
  DOCKER_TMP=$(mktemp -d) || exit 1
  if ! curl -fsSL https://get.docker.com -o "$DOCKER_TMP/get-docker.sh"; then
    echo "Error: Could not download the docker installation script." >&2
    echo 'Please check your internet connection and try again'
    rm -rf "$DOCKER_TMP"
    exit 1
  fi
  if ! $SUDO sh "$DOCKER_TMP/get-docker.sh"; then
    echo "Error: Could not install Docker." >&2
    echo 'Please check your docker installation and try again'
    rm -rf "$DOCKER_TMP"
    exit 1
  fi
  rm -rf "$DOCKER_TMP"
fi

if ! $SUDO docker compose version; then
  echo "Error: The docker compose plugin is not installed." >&2
  echo 'Please install it (package docker-compose-plugin) and try again'
  exit 1
fi

COMPOSE="$SUDO docker compose --project-directory $SOURCE_ROOT -f $COMPOSE_FILE"

# A new database means a first start: the app installs the license key
# itself and asks for an admin account.
[ -s "$DATABASE_SOURCE" ] && FIRST_START=false || FIRST_START=true

echo "> Creating the local database..."
# The database holds the session signing key, password hashes and the license:
# owner only. The app container runs as root, so it can still write to it.
if ! mkdir -p "$SOURCE_ROOT" || ! chmod 700 "$SOURCE_ROOT"; then
  echo "Error: Could not create the local database directory $SOURCE_ROOT." >&2
  echo 'Please check permissions and try again'
  exit 1
fi
if ! { [ -f "$DATABASE_SOURCE" ] || touch "$DATABASE_SOURCE"; } || ! chmod 600 "$DATABASE_SOURCE"; then
  echo "Error: Could not create the local database file $DATABASE_SOURCE." >&2
  echo 'Please check permissions and try again'
  exit 1
fi
if ! { [ -f "$LOGS_SOURCE" ] || touch "$LOGS_SOURCE"; } || ! chmod 600 "$LOGS_SOURCE"; then
  echo "Error: Could not create the logs file $LOGS_SOURCE." >&2
  echo 'Please check permissions and try again'
  exit 1
fi
if ! mkdir -p $IMAGES_SOURCE; then
  echo "Error: Could not create the images directory $IMAGES_SOURCE." >&2
  echo 'Please check permissions and try again'
  exit 1
fi

echo "> Checking the license with the download portal..."
if [ -z "$VERSION" ]; then
  if ! portal_get /v1/latest "$IMAGES_SOURCE/latest"; then
    echo 'Please check the license key and your internet connection and try again'
    exit 1
  fi
  VERSION=$(tr -d '[:space:]' <"$IMAGES_SOURCE/latest")
  rm -f "$IMAGES_SOURCE/latest"
  if ! valid_version "$VERSION"; then
    echo "Error: The download portal answered with an invalid version." >&2
    echo 'Please try again later or pass --version'
    exit 1
  fi
fi
APP_IMAGE="smartdecision:$VERSION"
APP_TAR="smartdecision-$VERSION-linux-$ARCH.tar"

echo "> Getting SmartDecision $VERSION ($ARCH)..."
if $SUDO docker image inspect "$APP_IMAGE" >/dev/null 2>&1; then
  echo "Version $VERSION is already loaded, skipping."
else
  if ! portal_get "/v1/releases/$VERSION/SHA256SUMS" "$IMAGES_SOURCE/SHA256SUMS"; then
    echo 'Please check the license key, the version and your internet connection and try again'
    exit 1
  fi
  if ! portal_get "/v1/releases/$VERSION/SHA256SUMS.sig" "$IMAGES_SOURCE/SHA256SUMS.sig"; then
    echo "Version $VERSION has no release signature; please install a newer version"
    rm -f "$IMAGES_SOURCE/SHA256SUMS"
    exit 1
  fi
  printf '%s\n' "$RELEASE_PUBLIC_KEY" >"$IMAGES_SOURCE/release-key.pem"
  if ! openssl pkeyutl -verify -pubin -inkey "$IMAGES_SOURCE/release-key.pem" -rawin \
    -in "$IMAGES_SOURCE/SHA256SUMS" -sigfile "$IMAGES_SOURCE/SHA256SUMS.sig" >/dev/null 2>&1; then
    echo "Error: The checksums of SmartDecision $VERSION are not signed by Wingravity." >&2
    echo 'The download may have been tampered with. Please contact support@smartdecision.io'
    rm -f "$IMAGES_SOURCE/SHA256SUMS" "$IMAGES_SOURCE/SHA256SUMS.sig" "$IMAGES_SOURCE/release-key.pem"
    exit 1
  fi

  verify_image() {
    awk -v f="$APP_TAR" '$2 == f || $2 == "*" f' "$IMAGES_SOURCE/SHA256SUMS" |
      (cd "$IMAGES_SOURCE" && sha256sum -c --status)
  }

  if [ -f "$IMAGES_SOURCE/$APP_TAR" ] && ! verify_image; then
    # A partial download resumes; a full-size file that fails the check starts over.
    remote_size=$(curl_auth "$KEY" -sSI "$PORTAL_URL/v1/releases/$VERSION/$APP_TAR" |
      tr -d '\r' | awk 'tolower($1) == "content-length:" { print $2 }')
    if [ -n "$remote_size" ] && [ "$(wc -c <"$IMAGES_SOURCE/$APP_TAR")" -ge "$remote_size" ]; then
      rm -f "$IMAGES_SOURCE/$APP_TAR"
    fi
  fi
  if ! [ -f "$IMAGES_SOURCE/$APP_TAR" ] || ! verify_image; then
    if ! curl_auth "$KEY" -fL -C - --progress-bar \
      -o "$IMAGES_SOURCE/$APP_TAR" "$PORTAL_URL/v1/releases/$VERSION/$APP_TAR"; then
      echo "Error: Could not download SmartDecision $VERSION." >&2
      echo 'Please check your internet connection and try again (the download resumes where it left off)'
      exit 1
    fi
  fi
  if ! verify_image; then
    echo "Error: The downloaded image failed the checksum verification." >&2
    echo "Please delete $IMAGES_SOURCE/$APP_TAR and try again"
    exit 1
  fi
  if ! $SUDO docker load -i "$IMAGES_SOURCE/$APP_TAR" || ! $SUDO docker image inspect "$APP_IMAGE" >/dev/null 2>&1; then
    echo "Error: Could not load the image $APP_IMAGE." >&2
    echo 'Please check your docker installation and try again'
    exit 1
  fi
  rm -f "$IMAGES_SOURCE/$APP_TAR" "$IMAGES_SOURCE/SHA256SUMS" "$IMAGES_SOURCE/SHA256SUMS.sig" "$IMAGES_SOURCE/release-key.pem"
fi

if [ "$LLM_MODE" = "builtin" ]; then
  echo "> Checking the language model..."
  if ! mkdir -p $MODELS_SOURCE; then
    echo "Error: Could not create the models directory $MODELS_SOURCE." >&2
    echo 'Please check permissions and try again'
    exit 1
  fi

  verify_model() {
    echo "$MODEL_SHA256  $MODELS_SOURCE/$MODEL_FILE" | sha256sum -c --status
  }

  if [ -f "$MODELS_SOURCE/$MODEL_FILE" ] && verify_model; then
    echo "Model already downloaded, skipping."
  else
    echo "Downloading the language model (~2.5 GB, resumable)..."
    if ! curl_auth "$KEY" -fL -C - --progress-bar -o "$MODELS_SOURCE/$MODEL_FILE" "$MODEL_URL"; then
      echo "Error: Could not download the language model." >&2
      echo 'Please check your internet connection and try again (the download resumes where it left off)'
      exit 1
    fi
    if ! verify_model; then
      echo "Error: The downloaded model failed the checksum verification." >&2
      echo "Please delete $MODELS_SOURCE/$MODEL_FILE and try again"
      exit 1
    fi
  fi
fi

echo "> Writing the configuration..."
# .env holds the LLM choice, the license key and possibly an API key: readable
# by the owner only. SMARTDECISION_DOWNLOAD_KEY is for this script's downloads.
# It is the license key, so the app also gets it and installs it on its first
# start (still replaceable in Settings, unlike SMARTDECISION_LICENSE).
# LLM_WARMUP preloads the model when "New decision" opens; it is off for
# the customer's own AI server, which may be shared or metered.
case $LLM_MODE in
  builtin) PROFILES=ai; LLM_URL=http://llm:8080/v1; LLM_MODEL=smartdecision; LLM_WARMUP=true ;;
  external) PROFILES=; LLM_WARMUP=false ;;
  none) PROFILES=; LLM_URL=; LLM_MODEL=; LLM_API_KEY=; LLM_WARMUP=false ;;
esac

# SMARTDECISION_URL is where apps and teammates reach the app. Keep an earlier
# run's value (it may have been edited), else use this server's address: the
# one it would reach the internet from, so not docker's bridge.
[ -z "$SERVER_URL" ] && SERVER_URL=$(env_value SMARTDECISION_URL)
[ -z "$SETUP_TOKEN" ] && SETUP_TOKEN=$(env_value SMARTDECISION_SETUP_TOKEN)
if [ -z "$SERVER_URL" ]; then
  ip=$(ip -4 route get 1.1.1.1 2>/dev/null | sed -n 's/.* src \([0-9.]*\).*/\1/p')
  [ -z "$ip" ] && ip=$(hostname -I 2>/dev/null | awk '{ print $1 }')
  [ -n "$ip" ] && SERVER_URL="http://$ip:8080"
fi

if ! (umask 077 && cat >$ENV_FILE <<EOF
COMPOSE_PROFILES=$PROFILES
LLM_URL='$LLM_URL'
LLM_MODEL='$LLM_MODEL'
LLM_API_KEY='$LLM_API_KEY'
LLM_WARMUP=$LLM_WARMUP
SMARTDECISION_LICENSE='$LICENSE'
SMARTDECISION_DOWNLOAD_KEY='$KEY'
SMARTDECISION_URL='$SERVER_URL'
SMARTDECISION_SETUP_TOKEN='$SETUP_TOKEN'
EOF
) || ! chmod 600 $ENV_FILE; then
  echo "Error: Could not write the configuration file $ENV_FILE." >&2
  echo 'Please check permissions and try again'
  exit 1
fi

if ! cat >$COMPOSE_FILE <<EOF
# Generated by install.sh; settings live in .env next to this file.
name: smartdecision
services:
  app:
    # Loaded by install.sh with docker load; there is no registry to pull from.
    image: $APP_IMAGE
    pull_policy: never
    container_name: $APP_IMAGE_NAME
    restart: unless-stopped
    ports:
      - "8080:8080"
    environment:
      LLM_URL: \${LLM_URL:-}
      LLM_MODEL: \${LLM_MODEL:-}
      LLM_API_KEY: \${LLM_API_KEY:-}
      LLM_WARMUP: \${LLM_WARMUP:-true}
      SMARTDECISION_LICENSE: \${SMARTDECISION_LICENSE:-}
      SMARTDECISION_DOWNLOAD_KEY: \${SMARTDECISION_DOWNLOAD_KEY:-}
      SMARTDECISION_URL: \${SMARTDECISION_URL:-}
      SMARTDECISION_SETUP_TOKEN: \${SMARTDECISION_SETUP_TOKEN:-}
    extra_hosts:
      - "host.docker.internal:host-gateway"
    volumes:
      - ./local.db:$TARGET_ROOT/local.db
      - ./all.log:$TARGET_ROOT/all.log

  # Not published on the host: only the app reaches it, over the compose network.
  llm:
    image: $LLM_IMAGE
    container_name: $LLM_CONTAINER_NAME
    profiles: [ai]
    restart: unless-stopped
    volumes:
      - ./models:/models:ro
      - ./llm-config.yaml:/app/config.yaml:ro
EOF
then
  echo "Error: Could not write the compose file $COMPOSE_FILE." >&2
  echo 'Please check permissions and try again'
  exit 1
fi

# llama-swap listens on :8080 and starts llama-server on the first request for
# the model, then stops it after `ttl` seconds without requests, so the ~4 GB
# of weights and KV cache are only resident while someone is authoring.
# /v1/models, /running and /health answer without loading the model.
if ! cat >$LLM_CONFIG_FILE <<EOF
# Generated by install.sh (re-running it overwrites this file).

# Seconds a cold start may take to load the weights. Slow disks (network
# volumes, Docker Desktop file sharing) can need several minutes for 2.5 GB.
healthCheckTimeout: 900
logToStdout: "both"
# Loading progress would be injected into the reasoning stream; the app asks
# for schema-constrained JSON and has no use for it.
sendLoadingState: false

models:
  # Must match the app's LLM_MODEL.
  smartdecision:
    # Sampling params mirror the dev Modelfile; the system prompt is sent
    # per-request by the app.
    # --ctx-size 8192: the system prompt is ~3k tokens, which leaves ~5k for
    # the policy and the table, at half the KV cache of 16k.
    # --parallel 1: one slot, so the system prompt cached by the app's
    # warm-up request is reused by the next generation.
    cmd: |
      /app/llama-server
      --port \${PORT}
      --host 127.0.0.1
      --model /models/$MODEL_FILE
      --ctx-size 8192
      --parallel 1
      --temp 0
      --seed 42
      --repeat-last-n 0
      --jinja
      --reasoning-budget 0
      --chat-template-kwargs '{"enable_thinking":false}'
    # Unload after 10 minutes idle. The app's warm window (utils.warmWindow)
    # is slightly shorter; keep them in step.
    ttl: 600
EOF
then
  echo "Error: Could not write the LLM configuration file $LLM_CONFIG_FILE." >&2
  echo 'Please check permissions and try again'
  exit 1
fi

if [ "$LLM_MODE" = "builtin" ]; then
  echo "> Pulling the built-in AI image..."
  if ! $COMPOSE pull llm; then
    echo "Error: Could not pull the built-in AI image." >&2
    echo 'Please check your internet connection and try again'
    exit 1
  fi
fi

if [ "$LLM_MODE" != "builtin" ]; then
  # Switching away from the built-in AI: stop it if an earlier run started it.
  $COMPOSE --profile ai rm -sf llm >/dev/null 2>&1
fi

echo "> Starting the application..."
if ! $COMPOSE up -d --remove-orphans; then
  echo "Error: Could not start SmartDecision." >&2
  echo 'Please check your docker installation and try again'
  exit 1
fi

if [ "$( $SUDO docker container inspect -f '{{.State.Running}}' $APP_IMAGE_NAME )" != "true" ]; then
  echo "Error: The container $APP_IMAGE_NAME is not running." >&2
  echo 'Please check the container logs and try again'
  $COMPOSE logs >&2
  exit 1
fi

if [ "$LLM_MODE" = "external" ]; then
  echo "> Checking your AI server..."
  # host.docker.internal only resolves inside the container; from here it is localhost.
  CHECK_URL=$(echo "$LLM_URL" | sed 's/host\.docker\.internal/localhost/')
  if [ -n "$LLM_API_KEY" ]; then
    check=$(curl_auth "$LLM_API_KEY" -s -o /dev/null -w '%{http_code}' "$CHECK_URL/models")
  else
    check=$(curl -s -o /dev/null -w '%{http_code}' "$CHECK_URL/models")
  fi
  if [ "$check" != "200" ]; then
    echo "[WARN] $LLM_URL/models answered '$check' from this host." >&2
    echo "Check the URL and key; you can change them in $ENV_FILE, then run: $COMPOSE up -d" >&2
  fi
fi

echo "> Setting up the CLI..."
ALIAS="alias smartdecision='$SUDO docker exec -it $APP_IMAGE_NAME $CLI_TARGET'"
if ! grep -qxF "$ALIAS" ~/.bashrc 2>/dev/null && ! echo "$ALIAS" >>~/.bashrc; then
  echo "Error: Could not create the alias smartdecision." >&2
  echo "Please add the alias manually: $ALIAS"
  exit 1
fi

printf "\n\033[1mSmartDecision $VERSION is up and running on ${SERVER_URL:-http://localhost:8080}\033[0m\n"
if [ "$FIRST_START" = true ] && [ -n "$SETUP_TOKEN" ]; then
  echo "Create the admin account with this link (keep it to yourself): ${SERVER_URL:-http://localhost:8080}/signup?invitation=$SETUP_TOKEN"
  echo "The license key is already installed."
elif [ "$FIRST_START" = true ]; then
  echo "Open it in a browser to create the admin account. The license key is already installed."
fi
if [ -n "$SERVER_URL" ]; then
  echo "Apps and teammates use this address; change it in Settings if they reach the server another way."
fi
case $LLM_MODE in
  builtin) echo "Built-in AI enabled: the model loads when you create a decision and unloads after 10 minutes idle." ;;
  external) echo "AI drafting uses $LLM_URL ($LLM_MODEL)." ;;
  none) echo "AI drafting is off. Re-run this script with --llm=builtin or --llm=external to enable it." ;;
esac
echo
