#!/bin/bash
# sync-upstream.sh - 同步原作者代码 + 保留我们的定制
#
# 用法：每次原作者有大改动时跑一次
#   HTTPS_PROXY=http://127.0.0.1:7890 bash sync-upstream.sh
#
# 做的事：
#   1. 备份我们的定制文件到 /tmp/wwf-ours/
#   2. 拉取原作者最新代码（github/main）
#   3. 把我们的定制文件加回去
#   4. 推到 Gitea
#
# 前提：已经 git remote add github https://github.com/jaxperro/winning-wallet-finder.git

set -e
cd "$(git rev-parse --show-toplevel)"

echo "=== 1. 备份我们的定制文件 ==="
BACKUP="/tmp/wwf-ours"
rm -rf "$BACKUP"
mkdir -p "$BACKUP/host" "$BACKUP/live"

# 我们的定制文件清单（新增定制文件必须加到这里！）
OUR_FILES=(
  "live/serve_dashboard.py"
  "live/bot_dashboard.html"
  "live/sync_live_floors.py"
  "live/setup_wallets.py"
  "host/mihomo-healthcheck.sh"
  "sync-upstream.sh"
  "DEPLOY.md"
  "USAGE.md"
  "日常使用.md"
  "问题排查与踩坑记录.md"
  "mihomo代理部署教程.md"
  "云端架构.md"
  "实盘配置.md"
  "常用命令.md"
  "项目流程.md"
  "钱包筛选流程.md"
  "每周Bench-Review流程.md"
  "同步作者代码指南.md"
)

for f in "${OUR_FILES[@]}"; do
  if [ -f "$f" ]; then
    mkdir -p "$BACKUP/$(dirname "$f")"
    cp "$f" "$BACKUP/$f"
    echo "  备份: $f"
  fi
done

# 也备份我们的钱包配置（要覆盖回作者的）
if [ -f "live/copybot.paper.json" ]; then
  cp "live/copybot.paper.json" "$BACKUP/live/copybot.paper.json.ours"
  echo "  备份: live/copybot.paper.json (我们的钱包配置)"
fi

echo ""
echo "=== 2. 拉取原作者最新代码 ==="
git fetch github
git checkout -B sync-upstream github/main
echo "  当前代码: $(git log --oneline -1)"

echo ""
echo "=== 3. 加回我们的定制文件 ==="
for f in "${OUR_FILES[@]}"; do
  if [ -f "$BACKUP/$f" ]; then
    mkdir -p "$(dirname "$f")"
    cp "$BACKUP/$f" "$f"
    echo "  恢复: $f"
  fi
done

echo ""
echo "=== 4. 恢复我们的钱包配置 ==="
if [ -f "$BACKUP/live/copybot.paper.json.ours" ]; then
  cp "$BACKUP/live/copybot.paper.json.ours" "live/copybot.paper.json"
  echo "  恢复: live/copybot.paper.json (我们的钱包)"
fi

# config.live.json 是 gitignored 的，不会被覆盖
if [ ! -f "config.live.json" ]; then
  cp config.live.example.json config.live.json
  echo "  创建: config.live.json (从模板，需要填 bankroll + 钱包)"
fi

echo ""
echo "=== 5. 提交 + 推送 ==="
git add -A
git commit -m "sync: upstream + our customizations (dashboard, healthcheck, docs, wallet setup)

Synced from github/main: $(git log --oneline github/main -1)
Our additions: serve_dashboard.py, bot_dashboard.html, mihomo-healthcheck.sh,
sync_live_floors.py, setup_wallets.py, 中文文档, 我们的钱包配置" || echo "  没有改动需要提交"

git push origin sync-upstream:main --force
echo ""
echo "=== 完成 ==="
echo "已推送到 Gitea main 分支"
echo ""
echo "下一步：在服务器上更新"
echo "  cd /opt/winning-wallet-finder"
echo "  systemctl stop copybot-live copybot-paper"
echo "  git fetch origin && git reset --hard origin/main"
echo "  rm -f copybot_state*.json copybot_fills*.jsonl live/copybot_live*.json"
echo "  cp host/mihomo-healthcheck.sh /opt/mihomo-healthcheck.sh"
echo "  cd live && python3 setup_wallets.py"
echo "  chown wwf:wwf ../config.live.json copybot.paper.json"
echo "  systemctl start copybot-paper copybot-live"
