#!/usr/bin/env bash
# 前台启动本机 Agent（Mac/Linux）
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
cd "$ROOT"

ENV_FILE="${NIANNIAN_CLIENT_ENV:-$ROOT/client/config/client-agent.env}"
if [[ -f "$ENV_FILE" ]]; then
  # shellcheck disable=SC1090
  set -a && source "$ENV_FILE" && set +a
fi

case "$(uname -s)" in
  Darwin)
    DEFAULT_HOME="$HOME/Library/Application Support/NianNian"
    export NIANNIAN_MODE="${NIANNIAN_MODE:-mac}"
    ;;
  Linux)
    DEFAULT_HOME="${XDG_DATA_HOME:-$HOME/.local/share}/niannian"
    export NIANNIAN_MODE="${NIANNIAN_MODE:-linux}"
    ;;
  *)
    DEFAULT_HOME="$HOME/.niannian"
    export NIANNIAN_MODE="${NIANNIAN_MODE:-mac}"
    ;;
esac

export NIANNIAN_HOME="${NIANNIAN_HOME:-$DEFAULT_HOME}"
mkdir -p "$NIANNIAN_HOME"

HOST="${NIANNIAN_AGENT_HOST:-127.0.0.1}"
PORT="${NIANNIAN_AGENT_PORT:-18765}"
STATIC_DIR="${NIANNIAN_CONSOLE_STATIC:-$ROOT/console/web/dist}"

if [[ ! -d "$STATIC_DIR" ]]; then
  echo "Console dist 不存在，先运行: bash client/scripts/build-console-client.sh" >&2
  exit 1
fi

if ! command -v niannian >/dev/null 2>&1; then
  echo "niannian CLI 未安装，先运行平台 install 脚本或: pip install -e \".[http]\"" >&2
  exit 1
fi

echo "Starting NianNian agent: $HOST:$PORT · home=$NIANNIAN_HOME · mode=$NIANNIAN_MODE"
exec niannian serve --host "$HOST" --port "$PORT" --static "$STATIC_DIR"
