#!/bin/bash
# deploy_sync.sh — 将MoFin脚本同步到知微cron部署目录
# MoFin是源码源头, ~/.hermes/profiles/position-analyst/scripts/ 是运行副本
# 用法: ./deploy_sync.sh [--check] [--diff]

SRC="/home/hmo/MoFin/scripts"
DST="/home/hmo/.hermes/profiles/position-analyst/scripts"
EXCLUDE="prepare_recommendation.py"  # profile独有，不覆盖

# 排除文件列表（用|分隔）
EXCLUDE_RE=""
for f in $EXCLUDE; do
  [ -n "$EXCLUDE_RE" ] && EXCLUDE_RE="$EXCLUDE_RE|"
  EXCLUDE_RE="$EXCLUDE_RE$f"
done

# 检查是否有差异
if [ "$1" = "--diff" ] || [ "$1" = "--check" ]; then
  changed=0
  for f in "$SRC"/*.py "$SRC"/*.sh; do
    base=$(basename "$f")
    # 跳过排除文件
    [ -n "$EXCLUDE_RE" ] && echo "$base" | grep -qE "^($EXCLUDE_RE)$" && continue
    dst="$DST/$base"
    if [ ! -f "$dst" ]; then
      echo "  ➕ $base (仅MoFin有)"
      changed=1
    elif ! diff -q "$f" "$dst" >/dev/null 2>&1; then
      echo "  🔄 $base (有差异)"
      changed=1
    fi
  done
  [ $changed -eq 0 ] && echo "  一致"
  exit 0
fi

# 实际同步
count=0
for f in "$SRC"/*.py "$SRC"/*.sh; do
  base=$(basename "$f")
  # 跳过排除文件
  [ -n "$EXCLUDE_RE" ] && echo "$base" | grep -qE "^($EXCLUDE_RE)$" && continue
  dst="$DST/$base"
  if [ ! -f "$dst" ]; then
    cp "$f" "$dst"
    echo "  ➕ $base → 已复制"
    count=$((count+1))
  elif ! diff -q "$f" "$dst" >/dev/null 2>&1; then
    cp "$f" "$dst"
    echo "  🔄 $base → 已同步"
    count=$((count+1))
  fi
done

# 确保权限一致
chmod 600 "$DST"/*.py "$DST"/*.sh 2>/dev/null

# 同步根目录核心库（MoFin根目录下的.py不被scripts/覆盖）
ROOT_SYNC=("mofin_db.py" "data_models.py")
for _f in "${ROOT_SYNC[@]}"; do
  _src="/home/hmo/MoFin/$_f"
  _dst="$DST/$_f"
  if [ -f "$_src" ]; then
    if [ ! -f "$_dst" ]; then
      cp "$_src" "$_dst"
      echo "  ➕ $_f (根→profile)"
      count=$((count+1))
    elif ! diff -q "$_src" "$_dst" >/dev/null 2>&1; then
      cp "$_src" "$_dst"
      echo "  🔄 $_f (根→profile)"
      count=$((count+1))
    fi
  fi
done

if [ $count -eq 0 ]; then
  echo "✅ 全部一致，无需同步"
else
  echo "✅ 同步了 $count 个文件"
fi

# 同步cron prompt注册版本（确保提示词管理系统与jobs.json一致）
python3 /home/hmo/MoFin/scripts/sync_cron_prompts.py 2>/dev/null || true
