#!/usr/bin/env bash
# Linux 客户端安装：pip + Console + systemd user service
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}/niannian"
SYSTEMD_USER="$HOME/.config/systemd/user"
SERVICE_NAME="niannian-agent.service"
ENV_DST="$ROOT/client/config/client-agent.env"

echo "==> NianNian Linux client install"
mkdir -p "$DATA_HOME" "$SYSTEMD_USER"

if [[ ! -f "$ENV_DST" ]]; then
  cp "$ROOT/client/config/client-agent.env.example" "$ENV_DST"
fi

cd "$ROOT"
python3 -m pip install -e ".[http]" --quiet
if [[ -f "$ROOT/console/web/dist/index.html" ]]; then
  echo "==> Console dist present, skip npm build"
else
  bash "$ROOT/client/scripts/build-console-client.sh"
fi

sed \
  -e "s|@REPO_ROOT@|$ROOT|g" \
  -e "s|@NIANNIAN_HOME@|$DATA_HOME|g" \
  "$ROOT/client/linux/niannian-agent.service" > "$SYSTEMD_USER/$SERVICE_NAME"

systemctl --user daemon-reload
systemctl --user enable --now "$SERVICE_NAME"

bash "$ROOT/client/scripts/health-check.sh"
echo "Done. http://127.0.0.1:18765/niannian/chat"
