#!/bin/bash

# omarchy:summary=Start a local model that is set up, with a show in the terminal while it loads
# omarchy:args=[recipe]
# omarchy:hidden=true

# omarchy-agent runs this in the agent's own terminal when the model it was
# asked to open on isn't up: a model takes a minute or so to load, and an empty
# terminal for that long looks broken. The model's weights pour into a field of
# characters from the left, as far across as the load is along going by how
# long the last one took, and the agent opens once the model answers.
#
# A model someone else already started (the panel's Start, a setup finishing)
# is waited for rather than started again. Ctrl+C leaves: the model carries on
# loading, since stopping a load halfway gains nothing.

STATUS_FILE="${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/agent-local/status.json"

status=$(omarchy-models status --json 2>/dev/null)
recipe=${1:-$(jq -r '.last // empty' <<<"$status" 2>/dev/null)}
if [[ -z $recipe ]]; then
  echo "No local model is set up. Set one up with: omarchy models use best text" >&2
  exit 1
fi

model_field() {
  jq -r --arg recipe "$recipe" ".models[\$recipe] | $1 // empty" 2>/dev/null
}

if [[ -z $(model_field '.recipe' <<<"$status") ]]; then
  echo "$recipe is not set up. Set it up with: omarchy models use $recipe" >&2
  exit 1
fi

model_state() {
  model_field '"\(.unit)/\(.sub_state)"'
}

[[ $(model_state <<<"$status") == "active/running" ]] && exit 0

name=$(model_field '.name' <<<"$status")
name=${name:-$recipe}
expected=$(model_field '.expected_load_seconds' <<<"$status")
since_ms=$(model_field '.since_ms' <<<"$status")
ram=$(model_field '.observed.ram_used_gib' <<<"$status")

# A model never timed, or a status without the numbers, leaves the bar to
# guess: these go into arithmetic, so only plain numbers get there.
expected=${expected%.*}
[[ $expected =~ ^[0-9]+$ ]] || expected=0
[[ $since_ms =~ ^[0-9]+$ ]] || since_ms=""

log=$(mktemp "${XDG_RUNTIME_DIR:-/tmp}/omarchy-agent-warmup.XXXXXX")
trap 'rm -f "$log"' EXIT
starter=""
case "$(model_state <<<"$status")" in
activating/* | installing/*)
  # Already on its way up: the bar picks up from when it started.
  ;;
*)
  since_ms=""
  # A session of its own, so Ctrl+C in the terminal doesn't reach the load.
  setsid omarchy-models start "$recipe" >"$log" 2>&1 </dev/null &
  starter=$!
  ;;
esac

now_ms() {
  local now=${EPOCHREALTIME/[.,]/}
  printf '%s' "${now:0:13}"
}

started_ms=${since_ms:-$(now_ms)}
expected_ms=$(( expected * 1000 ))

# 0 when the model is up, 1 when it failed, 2 while it is still loading.
loading() {
  if [[ -n $starter ]]; then
    kill -0 "$starter" 2>/dev/null && return 2
    wait "$starter"
    return $(( $? == 0 ? 0 : 1 ))
  fi

  case "$(model_state <"$STATUS_FILE")" in
  active/running) return 0 ;;
  activating/* | installing/*) return 2 ;;
  *)
    model_field '.error' <"$STATUS_FILE" >"$log"
    return 1
    ;;
  esac
}

failed() {
  echo "$name didn't start." >&2
  if [[ -s $log ]]; then
    cat "$log" >&2
  else
    echo "See why with: omarchy models logs $recipe" >&2
  fi
  # The terminal closes with this command, taking the reason with it.
  if [[ -t 0 && -t 2 ]]; then
    read -rsn1 -p $'\nPress any key to close' _
  fi
  exit 1
}

# Without a terminal there is nothing to draw on: wait quietly.
if [[ ! -t 0 || ! -t 1 ]]; then
  while true; do
    loading
    case $? in
    0) exit 0 ;;
    1) failed ;;
    esac
    sleep 1
  done
fi

# ------------------------------------------------------------------ the show

# The terminal's own sixteen colors, so the show wears the theme.
RESET=$'\e[0m' DIM=$'\e[90m' BOLD=$'\e[1m'
DEEP=$'\e[34m' MID=$'\e[36m' HOT=$'\e[35m' PEAK=$'\e[1;97m' SPARK=$'\e[1;33m' EDGE=$'\e[1;96m'
RAMP=(. : - = + '*' '#' % @)
SPARKS=('*' + "'" . '`')
SPINNER=('|' / - '\')
QUIPS=(
  "Waking the weights"
  "Teaching sand to think"
  "Aligning the tensors"
  "Warming up the attention heads"
  "Counting to a few billion"
  "Untangling the matrices"
  "Stretching the context window"
  "Polishing the logits"
  "Herding the parameters"
  "Brewing tokens"
  "Asking the GPU nicely"
  "Folding the embeddings"
)
[[ -n $ram && $ram != "0" && $ram != "0.0" ]] && QUIPS+=("Pouring $ram GB into memory")

mapfile -t SIN < <(awk 'BEGIN { for (i = 0; i < 64; i++) printf "%d\n", sin(i * 6.2831853 / 64) * 100 }')

restore() {
  printf '\e[?25h\e[?1049l%s' "$RESET"
  stty "$tty_settings" 2>/dev/null
}
tty_settings=$(stty -g 2>/dev/null)
trap 'restore; rm -f "$log"' EXIT
trap 'exit 130' INT TERM HUP
trap 'resized=1' WINCH
stty -echo 2>/dev/null
printf '\e[?1049h\e[?25l'

measure() {
  local size
  size=$(stty size 2>/dev/null)
  rows=${size% *}
  cols=${size#* }
  (( rows > 0 && cols > 0 )) || { rows=24; cols=80; }
  # The field leaves room for the title above and the line below, and
  # goes when the terminal is too small to hold it.
  width=$(( cols - 6 < 72 ? cols - 6 : 72 ))
  height=$(( rows - 8 < 11 ? rows - 8 : 11 ))
  (( width < 20 || height < 3 )) && height=0
  top=$(( (rows - height - 6) / 2 ))
  (( top < 0 )) && top=0
  left=$(( (cols - width - 2) / 2 ))
  (( left < 0 )) && left=0
  printf '\e[2J'
}

center() {
  # $1 is what's shown, to measure; $2 the same with its colors.
  local pad=$(( (cols - ${#1}) / 2 ))
  (( pad < 0 )) && pad=0
  printf -v line '%*s%s\e[K\n' "$pad" "" "$2"
  frame+=$line
}

# The model's name, letter-spaced, with a highlight sweeping across it.
title() {
  local spaced="" plain="" i char at=$(( tick % (${#name} + 12) - 4 ))
  for (( i = 0; i < ${#name}; i++ )); do
    char=${name:i:1}
    char=${char^^}
    plain+="$char "
    if (( i >= at - 1 && i <= at + 1 )); then
      spaced+="$PEAK$char$RESET "
    else
      spaced+="$BOLD$char$RESET "
    fi
  done
  if (( ${#plain} > cols - 2 )); then
    center "$name" "$BOLD$name$RESET"
  else
    center "${plain% }" "${spaced% }"
  fi
}

# Three sine waves drifting through each other make the plasma; each row's
# share of it ends at a ragged front that moves right as the model loads, with
# sparks thrown ahead and a few stars in the dark still to fill.
field() {
  local x y row color next value level front spark border
  local -a wave_x wave_y wave_d

  for (( x = 0; x < width; x++ )); do
    wave_x[x]=${SIN[(x * 3 + tick * 2) & 63]}
  done
  for (( y = 0; y < height; y++ )); do
    wave_y[y]=${SIN[(y * 7 - tick * 3) & 63]}
  done
  for (( x = 0; x < width + height; x++ )); do
    wave_d[x]=${SIN[(x * 2 + tick) & 63]}
  done

  printf -v border '%*s' "$width" ""
  border=${border// /-}
  printf -v row '%*s%s.%s.%s\e[K\n' "$left" "" "$DIM" "$border" "$RESET"
  frame+=$row

  for (( y = 0; y < height; y++ )); do
    front=$(( permille * (width + 3) / 1000 - 2 + SIN[(y * 9 + tick * 4) & 63] * 2 / 100 ))
    (( permille >= 1000 )) && front=$width
    printf -v row '%*s%s|' "$left" "" "$DIM"
    color=$DIM
    for (( x = 0; x < width; x++ )); do
      if (( x < front )); then
        value=$(( wave_x[x] + wave_y[y] + wave_d[x + y] + 300 ))
        level=$(( value * 9 / 601 ))
        if (( flash )); then next=$PEAK
        elif (( level < 3 )); then next=$DEEP
        elif (( level < 6 )); then next=$MID
        elif (( level < 8 )); then next=$HOT
        else next=$PEAK
        fi
        char=${RAMP[level]}
      elif (( x == front )); then
        next=$EDGE
        char=${SPINNER[(tick / 2 + y) & 3]}
      elif (( x <= front + 5 && (x * 31 + y * 17 + tick * 7) % 6 == 0 )); then
        next=$SPARK
        spark=$(( (x + y + tick) % ${#SPARKS[@]} ))
        char=${SPARKS[spark]}
      elif (( (x * 73 + y * 151 + tick / 8 * 37) % 89 == 0 )); then
        next=$DIM
        char="."
      else
        row+=" "
        continue
      fi
      if [[ $next != "$color" ]]; then
        row+="$RESET$next"
        color=$next
      fi
      row+=$char
    done
    frame+="$row$RESET$DIM|$RESET"$'\e[K\n'
  done

  printf -v row '%*s%s'"'"'%s'"'"'%s\e[K\n' "$left" "" "$DIM" "$border" "$RESET"
  frame+=$row
}

draw() {
  local elapsed_ms=$(( $(now_ms) - started_ms )) quip percent spinner i
  (( elapsed_ms < 0 )) && elapsed_ms=0

  # Straight to nine tenths over the time the last load took, then creeping:
  # the bar never claims to be done before the model is.
  if (( flash )); then
    permille=1000
  elif (( expected_ms == 0 )); then
    permille=$(( 950 * elapsed_ms / (elapsed_ms + 45000) ))
  elif (( elapsed_ms <= expected_ms )); then
    permille=$(( 900 * elapsed_ms / expected_ms ))
  else
    permille=$(( 900 + 90 * (elapsed_ms - expected_ms) / elapsed_ms ))
  fi
  percent=$(( permille / 10 ))

  frame=$'\e[H'
  for (( i = 0; i < top; i++ )); do
    frame+=$'\e[K\n'
  done
  title
  frame+=$'\e[K\n'
  (( height > 0 )) && field
  frame+=$'\e[K\n'

  if (( flash )); then
    center "$name is ready" "$PEAK$name is ready$RESET"
  else
    quip=${QUIPS[(elapsed_ms / 4000 + quip_offset) % ${#QUIPS[@]}]}
    spinner=${SPINNER[(tick / 2) & 3]}
    center "$spinner $quip... $percent%" "$EDGE$spinner$RESET $quip... $BOLD$percent%$RESET"
  fi
  frame+=$'\e[J'
  printf '%s' "$frame"
}

tick=0
flash=0
resized=1
quip_offset=$(( RANDOM % ${#QUIPS[@]} ))

while true; do
  if (( resized )); then
    resized=0
    measure
  fi
  draw
  # A read that times out is the frame's pause, and takes stray keypresses.
  read -rsn1 -t 0.06 _
  (( tick++ ))

  # The starter is a builtin's glance away; the status file costs a jq.
  if [[ -n $starter ]] || (( tick % 12 == 0 )); then
    loading
    case $? in
    0) break ;;
    1)
      restore
      trap 'rm -f "$log"' EXIT
      failed
      ;;
    esac
  fi
done

# Filled to the brim and lit up, for a moment, before the agent takes over.
flash=1
for (( i = 0; i < 10; i++ )); do
  draw
  read -rsn1 -t 0.06 _
  (( tick++ ))
done

exit 0
