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

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "${ROOT_DIR}"

# Load root env if present (API keys, etc.)
if [ -f "../../.env" ]; then
  set -a
  # shellcheck disable=SC1091
  source "../../.env"
  set +a
fi

export ENV="${ENV:-dev}"
export PORT="${PORT:-8002}"
export OLLAMA_URL="${OLLAMA_URL:-http://localhost:11434}"
# On NODA2 native runtime we prefer local memory-service.
# Set SOFIIA_FORCE_LOCAL_MEMORY=false to keep external URL from env.
if [ "${SOFIIA_FORCE_LOCAL_MEMORY:-true}" = "true" ]; then
  export MEMORY_SERVICE_URL="http://localhost:8000"
else
  export MEMORY_SERVICE_URL="${MEMORY_SERVICE_URL:-http://localhost:8000}"
fi
export ROUTER_URL="${ROUTER_URL:-http://144.76.224.179:9102}"
export GATEWAY_URL="${GATEWAY_URL:-http://144.76.224.179:9300}"

export SOFIIA_PREFERRED_CHAT_MODEL="${SOFIIA_PREFERRED_CHAT_MODEL:-ollama:qwen3:14b}"
export SOFIIA_OLLAMA_TIMEOUT_SEC="${SOFIIA_OLLAMA_TIMEOUT_SEC:-120}"
export SOFIIA_OLLAMA_VOICE_TIMEOUT_SEC="${SOFIIA_OLLAMA_VOICE_TIMEOUT_SEC:-45}"
export SOFIIA_OLLAMA_KEEP_ALIVE="${SOFIIA_OLLAMA_KEEP_ALIVE:-30m}"
export SOFIIA_OLLAMA_NUM_CTX="${SOFIIA_OLLAMA_NUM_CTX:-8192}"
export SOFIIA_OLLAMA_NUM_THREAD="${SOFIIA_OLLAMA_NUM_THREAD:-8}"
export SOFIIA_OLLAMA_NUM_GPU="${SOFIIA_OLLAMA_NUM_GPU:--1}"
export SOFIIA_OLLAMA_NUM_PREDICT_TEXT="${SOFIIA_OLLAMA_NUM_PREDICT_TEXT:-768}"

export SOFIIA_DATA_DIR="${SOFIIA_DATA_DIR:-$HOME/.sofiia/console-data}"
mkdir -p "${SOFIIA_DATA_DIR}"

export AISTALK_ENABLED="${AISTALK_ENABLED:-true}"
export AISTALK_URL="${AISTALK_URL:-http://127.0.0.1:9415}"
export AISTALK_API_KEY="${AISTALK_API_KEY:-}"

if [ -d "venv" ]; then
  # shellcheck disable=SC1091
  source venv/bin/activate
elif [ -d "../../venv" ]; then
  # shellcheck disable=SC1091
  source ../../venv/bin/activate
fi

echo "[sofiia-daemon] starting on 127.0.0.1:${PORT}"
echo "[sofiia-daemon] data: ${SOFIIA_DATA_DIR}"
echo "[sofiia-daemon] ollama: ${OLLAMA_URL}"
echo "[sofiia-daemon] model: ${SOFIIA_PREFERRED_CHAT_MODEL}"
echo "[sofiia-daemon] tune: ctx=${SOFIIA_OLLAMA_NUM_CTX} threads=${SOFIIA_OLLAMA_NUM_THREAD} gpu=${SOFIIA_OLLAMA_NUM_GPU} keep_alive=${SOFIIA_OLLAMA_KEEP_ALIVE}"
echo "[sofiia-daemon] aistalk: enabled=${AISTALK_ENABLED} url=${AISTALK_URL}"

exec python3 -m uvicorn app.main:app --host 127.0.0.1 --port "${PORT}"
