#!/bin/bash
# 新机器环境初始化（只需执行一次）
#
# 用法：在项目根目录执行
#   bash scripts/setup.sh
#
# 完成后重启终端（或 source ~/.zshrc）使 PATH 全局生效。

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
PUB_CACHE_BIN="$HOME/.pub-cache/bin"

# 前置检查：Flutter SDK 必须已安装
if ! command -v dart &> /dev/null; then
  echo "Error: dart not found."
  echo "Please install Flutter SDK first: https://docs.flutter.dev/get-started/install"
  exit 1
fi
if ! command -v flutter &> /dev/null; then
  echo "Error: flutter not found."
  echo "Please install Flutter SDK first: https://docs.flutter.dev/get-started/install"
  exit 1
fi

echo "=== customer-im-client 环境初始化 ==="
echo ""

# ---- Step 1: 安装全局工具 ----
echo "[1/7] 安装全局工具 (melos + mason_cli)..."
dart pub global activate melos
dart pub global activate mason_cli
echo ""

# ---- Step 2: 配置 PATH ----
echo "[2/7] 配置 PATH..."
if [[ "$SHELL" == */zsh ]]; then
  SHELL_CONFIG="$HOME/.zshrc"
elif [[ "$SHELL" == */bash ]]; then
  SHELL_CONFIG="$HOME/.bash_profile"
else
  SHELL_CONFIG="$HOME/.profile"
fi

PATH_LINE='export PATH="$PATH":"$HOME/.pub-cache/bin"'
if ! grep -qF ".pub-cache/bin" "$SHELL_CONFIG" 2>/dev/null; then
  echo "$PATH_LINE" >> "$SHELL_CONFIG"
  echo "  写入 PATH 到 $SHELL_CONFIG"
else
  echo "  PATH 已配置，跳过"
fi
export PATH="$PATH:$PUB_CACHE_BIN"   # 当前 session 立即生效
echo ""

# ---- Step 3: 安装项目依赖 ----
echo "[3/6] dart pub get..."
cd "$ROOT_DIR" && dart pub get
echo ""

# ---- Step 4: IDE 模块配置生成 ----
# 生成 .iml 和 .idea/modules.xml，IDE 靠这些文件识别各个包并显示 [melos_xxx] 标签。
# 这些文件在 .gitignore 中不入库，每台机器需要本地生成。
# 已有环境缺失标签时，单独执行 melos bootstrap 即可补全，无需重跑整个 setup。
echo "[4/6] melos bootstrap (生成 .iml + modules.xml)..."
cd "$ROOT_DIR" && "$PUB_CACHE_BIN/melos" bootstrap
echo ""

# ---- Step 4.5: 清理旧的 mason 缓存 ----
if [ -d "$ROOT_DIR/.mason" ]; then
    echo "  清理旧 .mason 目录..."
    rm -rf "$ROOT_DIR/.mason"
fi

if [ -f "$ROOT_DIR/mason-lock.json" ]; then
    echo "  清理旧 mason-lock.json..."
    rm -f "$ROOT_DIR/mason-lock.json"
fi

# ---- Step 5: 注册 mason bricks ----
echo "[5/7] mason get (注册本地 bricks)..."
cd "$ROOT_DIR" && "$PUB_CACHE_BIN/mason" get
echo ""

echo "[6/7] mason add clean_plugin_sdk bricks..."
if ! grep -qE '^\s*clean_plugin_sdk:' "$ROOT_DIR/mason.yaml" 2>/dev/null; then
  cd "$ROOT_DIR" && "$PUB_CACHE_BIN/mason" add clean_plugin_sdk --path ./mason/bricks/clean_plugin_sdk
else
  echo "  clean_plugin_sdk 已在 mason.yaml 中，跳過"
fi

# ---- Step 6: 首次代码生成 ----
echo "[7/7] melos run gen (首次代码生成)..."
cd "$ROOT_DIR" && "$PUB_CACHE_BIN/melos" run gen
echo ""

# ---- 验证 ----
echo "=== 验证 ==="
echo -n "melos : " && "$PUB_CACHE_BIN/melos" --version
echo -n "mason : " && "$PUB_CACHE_BIN/mason" --version
echo ""
echo "=== 完成！重启终端（或执行 source ${SHELL_CONFIG}）使 PATH 全局生效 ==="
