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

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
VENV_DIR="${ROOT_DIR}/.venv-macos"
PORT="${PORT:-9401}"
AURORA_ENV_FILE="${AURORA_ENV_FILE:-${HOME}/.sofiia/aurora.env}"
cd "${ROOT_DIR}"

if [ ! -x "${VENV_DIR}/bin/python" ]; then
  echo "[aurora-native] venv is missing. Run ./setup-native-macos.sh first."
  exit 1
fi

source "${VENV_DIR}/bin/activate"

# Optional local env file for secrets/runtime overrides.
if [ -f "${AURORA_ENV_FILE}" ]; then
  set -a
  # shellcheck disable=SC1090
  source "${AURORA_ENV_FILE}"
  set +a
fi

export AURORA_DATA_DIR="${AURORA_DATA_DIR:-${HOME}/.sofiia/aurora-data}"
export AURORA_MODELS_DIR="${AURORA_MODELS_DIR:-${AURORA_DATA_DIR}/models}"
export AURORA_PUBLIC_BASE_URL="${AURORA_PUBLIC_BASE_URL:-http://127.0.0.1:${PORT}}"
export AURORA_CORS_ORIGINS="${AURORA_CORS_ORIGINS:-*}"

# Apple Silicon acceleration profile.
export AURORA_FORCE_CPU="${AURORA_FORCE_CPU:-false}"
export AURORA_PREFER_MPS="${AURORA_PREFER_MPS:-true}"
export AURORA_ENABLE_VIDEOTOOLBOX="${AURORA_ENABLE_VIDEOTOOLBOX:-true}"

_read_keychain_secret() {
  local service_name="$1"
  security find-generic-password -s "${service_name}" -w 2>/dev/null || true
}

_read_first_keychain_secret() {
  local value=""
  local service=""
  for service in "$@"; do
    value="$(_read_keychain_secret "${service}")"
    if [ -n "${value}" ]; then
      printf '%s' "${value}"
      return 0
    fi
  done
  return 1
}

if [ -z "${KLING_ACCESS_KEY:-}" ]; then
  KLING_ACCESS_KEY="$(_read_first_keychain_secret "daarion.kling.access_key" "kling.access_key" "KLING_ACCESS_KEY" || true)"
fi
if [ -z "${KLING_SECRET_KEY:-}" ]; then
  KLING_SECRET_KEY="$(_read_first_keychain_secret "daarion.kling.secret_key" "kling.secret_key" "KLING_SECRET_KEY" || true)"
fi
export KLING_ACCESS_KEY="${KLING_ACCESS_KEY:-}"
export KLING_SECRET_KEY="${KLING_SECRET_KEY:-}"
export KLING_BASE_URL="${KLING_BASE_URL:-https://api.klingai.com}"
export KLING_TIMEOUT="${KLING_TIMEOUT:-60}"

mkdir -p "${AURORA_DATA_DIR}" "${AURORA_MODELS_DIR}"

echo "[aurora-native] starting on 127.0.0.1:${PORT}"
echo "[aurora-native] data: ${AURORA_DATA_DIR}"
echo "[aurora-native] models: ${AURORA_MODELS_DIR}"
echo "[aurora-native] force_cpu=${AURORA_FORCE_CPU} prefer_mps=${AURORA_PREFER_MPS} videotoolbox=${AURORA_ENABLE_VIDEOTOOLBOX}"
if [ -n "${KLING_ACCESS_KEY}" ] && [ -n "${KLING_SECRET_KEY}" ]; then
  echo "[aurora-native] kling: configured"
else
  echo "[aurora-native] kling: credentials missing"
fi

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