#!/usr/bin/env bash
# setup_mac.sh — One-shot installer for the local AI stack on macOS.
# Run from inside the mac_stack folder:
#   chmod +x setup_mac.sh && ./setup_mac.sh
set -euo pipefail

say() { printf "\033[1;36m==>\033[0m %s\n" "$*"; }
warn() { printf "\033[1;33m!! \033[0m%s\n" "$*"; }

# 1. Homebrew (if missing)
if ! command -v brew >/dev/null 2>&1; then
  say "Installing Homebrew..."
  /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
else
  say "Homebrew already installed."
fi

# 2. Ollama
if ! command -v ollama >/dev/null 2>&1; then
  say "Installing Ollama..."
  brew install --cask ollama
  warn "Open the Ollama app once from Applications so it stays running, then re-run this script."
  exit 0
else
  say "Ollama already installed."
fi

# 3. Models
say "Pulling models (this can take a while on first run)..."
ollama pull llama3.2
ollama pull nomic-embed-text
ollama pull hermes3:8b

# 4. Python venv + deps
if [ ! -d .venv ]; then
  say "Creating Python virtualenv at .venv ..."
  python3 -m venv .venv
fi
# shellcheck disable=SC1091
source .venv/bin/activate
say "Installing Python packages..."
pip install --upgrade pip >/dev/null
pip install -r requirements.txt

# 5. Build the "in the bones" model
say "Building the 'kru-ai' model from Modelfile..."
ollama create kru-ai -f Modelfile

# 6. Karpathy's blog corpus
if [ ! -d karpathy_blog ]; then
  say "Cloning Karpathy's blog repo..."
  git clone https://github.com/karpathy/karpathy.github.io karpathy_blog
else
  say "Karpathy blog repo already present."
fi

# 7. Starter notes folder
if [ ! -d notes ]; then
  mkdir notes
  cat > notes/about_me.md <<'EOF'
# About me

I am a student in Chiang Mai. My favourite food is khao soi.
My pet is a cat named Meow Meow.
EOF
  say "Created notes/ with one starter file. Add more .md files in there."
fi

say "Done. Try one of these from inside the .venv:"
echo "    ollama run kru-ai"
echo "    python tutor.py"
echo "    python karpathy_tutor.py"
echo "    python agent.py"
