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

# Ubuntu/systemd 前端启动入口。
# 运行生产构建后的 Next.js 服务；开发调试继续使用 scripts/start-webui.sh。

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

BACKEND_HOST="${CLAW_BACKEND_HOST:-127.0.0.1}"
BACKEND_PORT="${CLAW_BACKEND_PORT:-8765}"
FRONTEND_HOST="${CLAW_FRONTEND_HOST:-0.0.0.0}"
FRONTEND_PORT="${CLAW_FRONTEND_PORT:-3000}"
NPM_BIN="${CLAW_NPM_BIN:-$(command -v npm || true)}"

if [[ -n "${CLAW_NODE_BIN_DIR:-}" ]]; then
	export PATH="${CLAW_NODE_BIN_DIR}:${PATH}"
fi

if [[ -z "${NPM_BIN}" || ! -x "${NPM_BIN}" ]]; then
	echo "npm not found for frontend service." >&2
	echo "Run deploy again from a shell where npm is available: bash scripts/deploy-ubuntu.sh" >&2
	exit 1
fi

export CLAW_API_URL="${CLAW_API_URL:-http://${BACKEND_HOST}:${BACKEND_PORT}}"

cd "${ROOT_DIR}/frontend/app"
exec "${NPM_BIN}" run start -- --hostname "${FRONTEND_HOST}" --port "${FRONTEND_PORT}"
