#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
UNIT_NAME="agent-knowledge-atlas.service"
UNIT_SOURCE="$ROOT/web/$UNIT_NAME"
UNIT_TARGET="$HOME/.config/systemd/user/$UNIT_NAME"
ENV_FILE="$ROOT/web/cache/service.env"
HOST="${HOST:-100.114.68.27}"
PORT="${PORT:-18080}"
HEALTH_URL="${HEALTH_URL:-http://$HOST:$PORT/api/health}"

write_environment() {
  mkdir -p "$(dirname "$ENV_FILE")"
  {
    printf 'HOST=%s\n' "$HOST"
    printf 'PORT=%s\n' "$PORT"
    printf 'MODEL_API_LUNA_URL=%s\n' "${MODEL_API_LUNA_URL:-http://192.168.1.10:11435/v1}"
    printf 'MODEL_API_SOL_URL=%s\n' "${MODEL_API_SOL_URL:-http://192.168.1.10:11436/v1}"
    printf 'MODEL_LIGHT=%s\n' "${MODEL_LIGHT:-ChatGPT-5.6:Luna}"
    printf 'MODEL_FAST=%s\n' "${MODEL_FAST:-ChatGPT-5.6:Terra}"
    printf 'MODEL_LARGE=%s\n' "${MODEL_LARGE:-ChatGPT-5.6:Sol}"
  } >"$ENV_FILE"
}

install_unit() {
  mkdir -p "$(dirname "$UNIT_TARGET")"
  ln -sfn "$UNIT_SOURCE" "$UNIT_TARGET"
  write_environment
  systemctl --user daemon-reload
}

wait_for_health() {
  for _ in $(seq 1 30); do
    if curl -fsS --max-time 2 "$HEALTH_URL" >/dev/null 2>&1; then
      return 0
    fi
    sleep 0.5
  done
  return 1
}

start_server() {
  install_unit
  systemctl --user enable --now "$UNIT_NAME"
  if ! wait_for_health; then
    echo "Server did not become healthy" >&2
    journalctl --user -u "$UNIT_NAME" -n 60 --no-pager >&2 || true
    return 1
  fi
  echo "Agent Knowledge Atlas started"
  echo "Health: $HEALTH_URL"
}

stop_server() {
  if systemctl --user is-active --quiet "$UNIT_NAME"; then
    systemctl --user stop "$UNIT_NAME"
    echo "Agent Knowledge Atlas stopped"
  else
    echo "Agent Knowledge Atlas is not running"
  fi
}

status_server() {
  systemctl --user is-active "$UNIT_NAME"
  curl -fsS --max-time 5 "$HEALTH_URL"
  echo
}

case "${1:-status}" in
  install)
    install_unit
    systemctl --user enable "$UNIT_NAME"
    echo "Installed $UNIT_NAME"
    ;;
  start) start_server ;;
  stop) stop_server ;;
  restart)
    install_unit
    systemctl --user restart "$UNIT_NAME"
    wait_for_health
    echo "Agent Knowledge Atlas restarted"
    ;;
  status) status_server ;;
  logs) journalctl --user -u "$UNIT_NAME" -n "${LINES:-80}" --no-pager ;;
  *)
    echo "Usage: $0 {install|start|stop|restart|status|logs}" >&2
    exit 2
    ;;
esac
