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

# Ubuntu/systemd 后端启动入口。
# 配置从项目根目录的 .env.deploy 读取；该文件只保存在部署机器本地，不提交到 git。

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ENV_FILE="${ROOT_DIR}/.env.deploy"

if [[ -f "${ENV_FILE}" ]]; then
	# shellcheck disable=SC1090
	source "${ENV_FILE}"
else
	echo "Missing deploy config: ${ENV_FILE}" >&2
	echo "Run: bash scripts/deploy-ubuntu.sh" >&2
	exit 1
fi

export OPENAI_API_KEY
export OPENAI_BASE_URL="${OPENAI_BASE_URL:-http://model.mify.ai.srv/v1}"
export OPENAI_MODEL="${OPENAI_MODEL:-tongyi/deepseek-v4-pro}"
export OPENAI_TIMEOUT_SECONDS="${OPENAI_TIMEOUT_SECONDS:-3600}"
export CLAW_MODEL_IDLE_TIMEOUT_SECONDS="${CLAW_MODEL_IDLE_TIMEOUT_SECONDS:-${OPENAI_TIMEOUT_SECONDS}}"

# 后端也会调用 Node 生态工具，例如 feishu-mcp-pro。systemd 不读取交互式
# shell 的 nvm 配置，所以需要把部署时记录的 Node 路径显式传给 Python 进程。
if [[ -n "${CLAW_NODE_BIN_DIR:-}" ]]; then
	export PATH="${CLAW_NODE_BIN_DIR}:${PATH}"
fi
export CLAW_NPM_BIN="${CLAW_NPM_BIN:-}"
export CLAW_NPX_BIN="${CLAW_NPX_BIN:-}"
export CLAW_NODE_BIN="${CLAW_NODE_BIN:-}"
export CLAW_NODE_BIN_DIR="${CLAW_NODE_BIN_DIR:-}"

BACKEND_HOST="${CLAW_BACKEND_HOST:-127.0.0.1}"
BACKEND_PORT="${CLAW_BACKEND_PORT:-8765}"
PYTHON_BIN="${CLAW_PYTHON_BIN:-${ROOT_DIR}/.venv/bin/python}"

exec "${PYTHON_BIN}" -m src.gui \
	--host "${BACKEND_HOST}" \
	--port "${BACKEND_PORT}" \
	--cwd "${ROOT_DIR}" \
	--timeout-seconds "${OPENAI_TIMEOUT_SECONDS}" \
	--session-dir "${ROOT_DIR}/.port_sessions/agent" \
	--allow-write \
	--allow-shell \
	--no-browser
