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

ENV_FILE="${MNOTE_LIGHTRAG_ENV_FILE:-/mnt/Data1T/Mnote_data/lightrag/LightRAG/.env}"
PYTHON="${MNOTE_PYTHON:-/usr/bin/python3}"
SERVER="${MNOTE_LIGHTRAG_MCP_SERVER:-/mnt/Data1T/mnote/scripts/mnote-lightrag-mcp-server.py}"

read_env_value() {
  local key="$1"
  local file="$2"
  if [[ ! -f "$file" ]]; then
    return 0
  fi
  grep -E "^${key}=" "$file" | tail -n 1 | sed -E "s/^${key}=//" | sed -E 's/^"(.*)"$/\1/' | sed -E "s/^'(.*)'$/\1/"
}

HOST_VALUE="${LIGHTRAG_HOST:-$(read_env_value HOST "$ENV_FILE")}"
PORT_VALUE="${LIGHTRAG_PORT:-$(read_env_value PORT "$ENV_FILE")}"
API_KEY_VALUE="${LIGHTRAG_API_KEY:-$(read_env_value LIGHTRAG_API_KEY "$ENV_FILE")}"

HOST_VALUE="${HOST_VALUE:-127.0.0.1}"
PORT_VALUE="${PORT_VALUE:-9621}"

if [[ ! -x "$PYTHON" ]]; then
  echo "python not found or not executable: $PYTHON" >&2
  exit 127
fi

if [[ ! -f "$SERVER" ]]; then
  echo "MNote LightRAG MCP server not found: $SERVER" >&2
  exit 127
fi

export LIGHTRAG_HOST="$HOST_VALUE"
export LIGHTRAG_PORT="$PORT_VALUE"
export LIGHTRAG_API_KEY="$API_KEY_VALUE"

exec "$PYTHON" "$SERVER" "$@"
