#!/usr/bin/env bash
#
# The Model Router — installer
# Installs four helper agents and one routing rule into ~/.claude so your
# assistant picks the right model and effort for each task.
#
# It is deliberately short and readable. It NEVER deletes anything: if a file
# already exists it is backed up first. It tells you exactly what it changed.
#
set -euo pipefail

BASE_URL="https://model-router.herfrontier.workers.dev"
DEST="$HOME/.claude"
AGENTS="$DEST/agents"
LINE="Before any substantial task, choose the model and effort using ~/.claude/MODEL_ROUTING.md."

say(){ printf '%s\n' "$*"; }

say ""
say "  The Model Router · installing into ~/.claude"
say "  ------------------------------------------------"

mkdir -p "$AGENTS"

stamp="$(date +%Y%m%d-%H%M%S)"
fetch(){
  # $1 remote path under BASE_URL, $2 local destination
  if [ -f "$2" ]; then
    cp "$2" "$2.bak-$stamp"
    say "  kept your existing $(basename "$2") as $(basename "$2").bak-$stamp"
  fi
  if curl -fsSL "$BASE_URL/$1" -o "$2"; then
    say "  installed $(basename "$2")"
  else
    say "  could not download $1 — check your connection and try again" >&2
    exit 1
  fi
}

fetch "starter-kit/MODEL_ROUTING.md" "$DEST/MODEL_ROUTING.md"
for a in writer builder analyst fast-worker; do
  fetch "starter-kit/agents/$a.md" "$AGENTS/$a.md"
done

# Wire it into CLAUDE.md so it is applied every session (idempotent).
CLAUDE_MD="$DEST/CLAUDE.md"
if [ -f "$CLAUDE_MD" ] && grep -qF "MODEL_ROUTING.md" "$CLAUDE_MD"; then
  say "  your CLAUDE.md already points at the rule, left it as is"
else
  printf '\n%s\n' "$LINE" >> "$CLAUDE_MD"
  say "  added one line to ~/.claude/CLAUDE.md"
fi

say "  ------------------------------------------------"
say "  Done. Restart Claude Code and it routes tasks on its own."
say ""
say "  Make it yours (two quick edits):"
say "    1. Set what counts as private for you:  ~/.claude/MODEL_ROUTING.md"
say "    2. Put your own voice on the writer:    ~/.claude/agents/writer.md"
say ""
say "  To remove it later: delete those five files from ~/.claude and"
say "  ~/.claude/agents, and remove the one line from ~/.claude/CLAUDE.md."
say ""
