#!/usr/bin/env bash
# ---------------------------------------------------------------------------
# offline-ai.sh — put the board's thinking on your own machine.
#
# Installs and starts Ollama with an open-source GPT model, opened to the
# Sovereign app so the boardroom can reason with no internet connection.
#
#   ./offline-ai.sh                 install (if needed), pull the model, start
#   ./offline-ai.sh --model llama3.1:8b   use a smaller/faster model
#   ./offline-ai.sh --check         report what is installed and running
#
# Default model: gpt-oss:20b  (open-weight GPT, ~14 GB, needs 16 GB memory)
# Lighter choices: gpt-oss:20b > llama3.1:8b > qwen2.5:7b > phi4-mini
# ---------------------------------------------------------------------------
set -euo pipefail

MODEL="${SOVEREIGN_MODEL:-gpt-oss:20b}"
CHECK=0
while [ $# -gt 0 ]; do
  case "$1" in
    --model) MODEL="$2"; shift 2 ;;
    --check) CHECK=1; shift ;;
    -h|--help) sed -n '2,16p' "$0"; exit 0 ;;
    *) echo "Unknown option: $1"; exit 1 ;;
  esac
done

# The app runs in a browser or in the desktop app, so Ollama must accept
# requests from a page. Without this it refuses them and the board stays cloud-side.
export OLLAMA_ORIGINS="${OLLAMA_ORIGINS:-*}"
export OLLAMA_HOST="${OLLAMA_HOST:-127.0.0.1:11434}"

if [ "$CHECK" = "1" ]; then
  if command -v ollama >/dev/null 2>&1; then echo "Ollama installed: $(ollama --version 2>/dev/null | head -1)"; else echo "Ollama is not installed."; fi
  if curl -sf "http://$OLLAMA_HOST/api/tags" >/dev/null 2>&1; then
    echo "Ollama is running at http://$OLLAMA_HOST"
    curl -s "http://$OLLAMA_HOST/api/tags" | grep -o '"name":"[^"]*"' | cut -d'"' -f4 | sed 's/^/  model: /'
  else
    echo "Ollama is not answering at http://$OLLAMA_HOST"
  fi
  exit 0
fi

if ! command -v ollama >/dev/null 2>&1; then
  echo "Installing Ollama..."
  case "$(uname -s)" in
    Darwin)
      if command -v brew >/dev/null 2>&1; then brew install ollama
      else echo "Download the Mac installer from https://ollama.com/download and run this script again."; exit 1; fi ;;
    Linux) curl -fsSL https://ollama.com/install.sh | sh ;;
    *) echo "On Windows, install Ollama from https://ollama.com/download and run this script in Git Bash or WSL."; exit 1 ;;
  esac
fi

if ! curl -sf "http://$OLLAMA_HOST/api/tags" >/dev/null 2>&1; then
  echo "Starting Ollama at http://$OLLAMA_HOST ..."
  ollama serve >/tmp/sovereign-ollama.log 2>&1 &
  for _ in $(seq 1 30); do
    curl -sf "http://$OLLAMA_HOST/api/tags" >/dev/null 2>&1 && break
    sleep 1
  done
fi

echo "Pulling $MODEL (first time only — this is a large download)..."
ollama pull "$MODEL"

echo
echo "Ready."
echo "  address : http://$OLLAMA_HOST"
echo "  model   : $MODEL"
echo "In the app, open Boardroom → Offline engine, switch it on, and press Test."
echo "Leave this window open while you use the board offline."
wait
