#!/bin/sh
# Tech AI monkey — application-menu launcher (installed by the .deb).
# You do not need this in a terminal; use "tech-ai" directly there.
#
# Why this exists: a desktop launcher gets no interactive terminal that can
# answer "Sign in now? [Y/n]", so the first run signs the user in through the
# browser itself and only then starts the chat. It also keeps the window open
# on error, so the message can actually be read instead of flashing past.

TECH_AI=""
if [ -x /usr/bin/tech-ai ]; then
  TECH_AI=/usr/bin/tech-ai
elif [ -x /usr/local/bin/tech-ai ]; then
  TECH_AI=/usr/local/bin/tech-ai
fi

run_cli() {
  if [ -n "$TECH_AI" ]; then
    "$TECH_AI" "$@"
  elif [ -f /usr/share/tech-ai-cli/index.js ]; then
    if command -v node >/dev/null 2>&1; then
      node /usr/share/tech-ai-cli/index.js "$@"
    else
      printf 'Node.js mangler. Installer nodejs (>= 18) og prov igjen.\n' >&2
      return 127
    fi
  else
    printf 'tech-ai er ikke installert. Installer .deb-pakken pa nytt.\n' >&2
    return 127
  fi
}

have_credentials() {
  _dir="${TECH_AI_CONFIG_DIR:-$HOME/.config/tech-ai}"
  [ -f "$_dir/credentials.json" ]
}

status=0
if [ "$#" -eq 0 ] && ! have_credentials; then
  printf '\nForste gang: du ma logge inn for a bruke Tech AI monkey.\n'
  printf 'Nettleseren din apnes — logg inn med Google eller e-post.\n\n'
  if run_cli login; then
    printf '\n'
    run_cli chat || status=$?
  else
    status=$?
    printf '\nInnloggingen ble ikke fullfort.\n' >&2
  fi
else
  run_cli "$@" || status=$?
fi

if [ -t 0 ]; then
  printf '\nTrykk Enter for a lukke dette vinduet... '
  read -r _ || true
fi

exit $status
