#!/usr/bin/env bash
# ============================================================
# LambdaAgentPaaS — Mac/Linux Native 安装（无 Docker）
#
# 用法:
#   ./deploy/install-native.sh          # 安装到 venv
#   ./deploy/install-native.sh --start  # 安装后直接启动
#
# 要求: Python 3.10+,  Node.js 18+
# ============================================================
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
VENV_DIR="${PROJECT_DIR}/.venv"
DATA_DIR="${HOME}/.agentpaas/data"
ENV_FILE="${HOME}/.agentpaas/.env"

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
BLUE='\033[0;34m'; BOLD='\033[1m'; NC='\033[0m'
info()    { echo -e "${BLUE}ℹ ${NC}$*"; }
success() { echo -e "${GREEN}✅ $*${NC}"; }
warn()    { echo -e "${YELLOW}⚠️  $*${NC}"; }
error()   { echo -e "${RED}❌ $*${NC}" >&2; exit 1; }

START_AFTER=""
for arg in "$@"; do [[ "$arg" == "--start" ]] && START_AFTER=1; done

echo -e "\n${BOLD}LambdaAgentPaaS Native 安装${NC}\n"

# ── 检查 Python ──────────────────────────────────────────────
PY=""
for candidate in python3.12 python3.11 python3.10 python3 python; do
  if command -v "$candidate" &>/dev/null; then
    ver=$("$candidate" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" 2>/dev/null || true)
    major=$(echo "$ver" | cut -d. -f1)
    minor=$(echo "$ver" | cut -d. -f2)
    if (( major > 3 )) || (( major == 3 && minor >= 10 )); then
      PY="$candidate"; break
    fi
  fi
done

[[ -z "$PY" ]] && error "需要 Python 3.10+。请从 https://www.python.org/ 安装后重试。"
info "使用 Python: $($PY --version)"

# ── 检查 Node.js ─────────────────────────────────────────────
if ! command -v node &>/dev/null; then
  error "需要 Node.js 18+。请从 https://nodejs.org/ 安装后重试。"
fi
NODE_VER=$(node -e "process.stdout.write(process.version.replace('v',''))" 2>/dev/null)
NODE_MAJOR=$(echo "$NODE_VER" | cut -d. -f1)
(( NODE_MAJOR < 18 )) && error "需要 Node.js 18+（当前: v${NODE_VER}）"
info "使用 Node.js: v${NODE_VER}"

# ── 创建虚拟环境 ─────────────────────────────────────────────
if [[ ! -d "$VENV_DIR" ]]; then
  info "创建 Python 虚拟环境..."
  "$PY" -m venv "$VENV_DIR"
fi

VENV_PY="${VENV_DIR}/bin/python"
VENV_PIP="${VENV_DIR}/bin/pip"

# ── 安装 Python 依赖 ─────────────────────────────────────────
info "安装 Python 依赖（首次约 2-3 分钟）..."
cd "$PROJECT_DIR"

# 国内网络可取消注释以下行加速
# PIP_OPTS="-i https://pypi.tuna.tsinghua.edu.cn/simple"
PIP_OPTS=""

$VENV_PIP install --upgrade pip $PIP_OPTS -q
$VENV_PIP install -e "lambdagent[all]" $PIP_OPTS -q
$VENV_PIP install -e "agentpaas[all]" $PIP_OPTS -q
$VENV_PIP install pymupdf $PIP_OPTS -q
success "Python 依赖安装完成"

# ── 构建前端 ─────────────────────────────────────────────────
info "安装前端依赖..."
cd "${PROJECT_DIR}/webui"
npm ci --prefer-offline --loglevel=error

info "构建前端..."
npm run build
success "前端构建完成 → webui-dist/"

cd "$PROJECT_DIR"

# ── 初始化数据目录 ────────────────────────────────────────────
mkdir -p "${DATA_DIR}/instances" "${DATA_DIR}/knowledge_bases" "${DATA_DIR}/logs"
chmod 700 "${HOME}/.agentpaas" 2>/dev/null || true

# ── 初始化配置文件 ────────────────────────────────────────────
if [[ ! -f "$ENV_FILE" ]]; then
  cp "${PROJECT_DIR}/.env.template" "$ENV_FILE"
  MASTER_KEY=$($VENV_PY -c "import secrets; print(secrets.token_hex(32))")
  sed -i.bak "s|^AGENTPAAS_DATA_DIR=.*|AGENTPAAS_DATA_DIR=${DATA_DIR}|" "$ENV_FILE"
  sed -i.bak "s|^AGENTPAAS_MASTER_KEY=.*|AGENTPAAS_MASTER_KEY=${MASTER_KEY}|" "$ENV_FILE"
  rm -f "${ENV_FILE}.bak"
  success "配置文件已创建: $ENV_FILE"
  warn "请编辑 ${ENV_FILE} 填写至少一个 LLM API Key"
fi

# ── 创建启动脚本 ─────────────────────────────────────────────
LAUNCHER="${HOME}/.agentpaas/run.sh"
cat > "$LAUNCHER" << LAUNCHER_SCRIPT
#!/usr/bin/env bash
# LambdaAgentPaaS 启动器（由 install-native.sh 生成）
set -a
source "${ENV_FILE}"
set +a
export AGENTPAAS_DATA_DIR="${DATA_DIR}"
cd "${PROJECT_DIR}"
exec "${VENV_PY}" -m agentpaas serve --host 0.0.0.0 --port "\${AGENTPAAS_PORT:-8000}"
LAUNCHER_SCRIPT
chmod +x "$LAUNCHER"

# ── macOS LaunchAgent（可选自动启动）────────────────────────
if [[ "$OSTYPE" == "darwin"* ]]; then
  PLIST_DIR="${HOME}/Library/LaunchAgents"
  PLIST_FILE="${PLIST_DIR}/com.lambdagentpaas.plist"
  mkdir -p "$PLIST_DIR"
  cat > "$PLIST_FILE" << PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>com.lambdagentpaas</string>
  <key>ProgramArguments</key>
  <array>
    <string>${LAUNCHER}</string>
  </array>
  <key>RunAtLoad</key>
  <false/>
  <key>StandardOutPath</key>
  <string>${DATA_DIR}/logs/agentpaas.log</string>
  <key>StandardErrorPath</key>
  <string>${DATA_DIR}/logs/agentpaas.err.log</string>
  <key>EnvironmentVariables</key>
  <dict>
    <key>AGENTPAAS_DATA_DIR</key>
    <string>${DATA_DIR}</string>
  </dict>
</dict>
</plist>
PLIST
  success "macOS LaunchAgent 已创建: $PLIST_FILE"
  info "开机自启: launchctl load $PLIST_FILE"
fi

# ── 打印完成信息 ─────────────────────────────────────────────
echo ""
echo -e "${GREEN}╔══════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║  ✅ LambdaAgentPaaS 安装完成！              ║${NC}"
echo -e "${GREEN}╠══════════════════════════════════════════════╣${NC}"
echo -e "${GREEN}║  启动命令: ~/.agentpaas/run.sh              ║${NC}"
echo -e "${GREEN}║  配置文件: ${ENV_FILE}${NC}"
echo -e "${GREEN}║  数据目录: ${DATA_DIR}${NC}"
echo -e "${GREEN}╚══════════════════════════════════════════════╝${NC}"
echo ""

if [[ -n "$START_AFTER" ]]; then
  info "正在启动服务..."
  exec "$LAUNCHER"
fi
