#!/bin/bash
# ─────────────────────────────────────────────────
# 工作手机 实时热更新 (监听文件变化 → 自动编译部署)
# ─────────────────────────────────────────────────
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"

echo "═══════════════════════════════════════"
echo "  工作手机 热更新模式"
echo "  监听: app/src/ 目录变化"
echo "  Ctrl+C 退出"
echo "═══════════════════════════════════════"
echo ""

if ! command -v fswatch &>/dev/null; then
    echo "需要安装 fswatch: brew install fswatch"
    echo "或手动运行: ./deploy.sh"
    exit 1
fi

DEBOUNCE_SEC=3
LAST_BUILD=0
BUILD_LOCK="/tmp/workphone-hotdeploy.lock"
rm -f "$BUILD_LOCK"

do_deploy() {
    local NOW=$(date +%s)
    local ELAPSED=$((NOW - LAST_BUILD))
    if [[ "$ELAPSED" -lt "$DEBOUNCE_SEC" ]]; then return; fi
    if [[ -f "$BUILD_LOCK" ]]; then return; fi

    touch "$BUILD_LOCK"
    LAST_BUILD=$NOW

    echo ""
    echo "──── $(date '+%H:%M:%S') 检测到变化，编译部署中... ────"
    if bash "$SCRIPT_DIR/deploy.sh"; then
        echo "──── $(date '+%H:%M:%S') 热更新完成 ✓ ────"
    else
        echo "──── $(date '+%H:%M:%S') 编译失败 ✗ ────"
    fi
    rm -f "$BUILD_LOCK"
}

export -f do_deploy
export SCRIPT_DIR DEBOUNCE_SEC LAST_BUILD BUILD_LOCK

echo "首次编译部署..."
do_deploy

echo ""
echo "开始监听文件变化..."
fswatch -o \
    --exclude ".*build.*" \
    --exclude ".*\.gradle.*" \
    --exclude ".*\.DS_Store" \
    "$SCRIPT_DIR/app/src/" | while read _; do
    do_deploy
done
