name: 上游同步 | Upstream Sync

permissions:
  contents: write
  issues: write
  actions: write
  pull-requests: write

on:
  # 默认关闭自动同步，仅支持手动触发
  # schedule:
  #   - cron: '0 */6 * * *' # every 6 hours
  workflow_dispatch:
    inputs:
      add_comment:
        description: '是否在同步后添加评论 | Add comment after sync'
        required: false
        default: true
        type: boolean

jobs:
  sync_latest_from_upstream:
    name: 同步上游最新提交 | Sync latest commits from upstream repo
    runs-on: ubuntu-latest
    if: ${{ github.event.repository.fork }}

    steps:
      - uses: actions/checkout@v4

      - name: 清理失败通知 | Clean issue notice
        uses: actions-cool/issues-helper@v3
        with:
          actions: 'close-issues'
          labels: '🚨 Sync Fail'

      - name: 同步上游变更 | Sync upstream changes
        id: sync
        uses: aormsby/Fork-Sync-With-Upstream-action@v3.4
        with:
          upstream_sync_repo: oiov/wr.do
          upstream_sync_branch: main
          target_sync_branch: main
          target_repo_token: ${{ secrets.GITHUB_TOKEN }} # automatically generated, no need to set
          test_mode: false

      - name: 获取最新提交信息 | Get latest commit info
        if: success()
        id: commit_info
        run: |
          # 获取最新的 commit SHA 和信息
          LATEST_COMMIT=$(git rev-parse HEAD)
          COMMIT_MESSAGE=$(git log -1 --pretty=format:"%s")
          COMMIT_AUTHOR=$(git log -1 --pretty=format:"%an")
          SYNC_TIME=$(date -u +"%Y-%m-%d %H:%M:%S UTC")

          echo "latest_commit=$LATEST_COMMIT" >> $GITHUB_OUTPUT
          echo "commit_message=$COMMIT_MESSAGE" >> $GITHUB_OUTPUT
          echo "commit_author=$COMMIT_AUTHOR" >> $GITHUB_OUTPUT
          echo "sync_time=$SYNC_TIME" >> $GITHUB_OUTPUT

      - name: 添加同步评论 | Add sync comment to commit
        if: success() && github.event.inputs.add_comment == 'true'
        uses: actions/github-script@v7
        with:
          script: |
            const commitSha = '${{ steps.commit_info.outputs.latest_commit }}';
            const syncTime = '${{ steps.commit_info.outputs.sync_time }}';
            const commitMsg = '${{ steps.commit_info.outputs.commit_message }}';
            const commitAuthor = '${{ steps.commit_info.outputs.commit_author }}';

            const commentBody = `## 🔄 同步成功 | Sync Successful

            **同步时间 | Sync Time:** ${syncTime}
            **源仓库 | Source Repository:** [oiov/wr.do](https://github.com/oiov/wr.do)
            **同步分支 | Sync Branch:** main → main
            **最新提交 | Latest Commit:** ${commitMsg}
            **提交作者 | Commit Author:** ${commitAuthor}

            ---
            *此评论由 GitHub Actions 自动生成 | This comment was automatically generated by GitHub Actions*`;

            try {
              await github.rest.repos.createCommitComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                commit_sha: commitSha,
                body: commentBody
              });
              console.log('✅ 成功添加同步评论到 commit:', commitSha);
            } catch (error) {
              console.log('❌ 添加评论失败:', error.message);
            }

      - name: 同步检查 | Sync check
        if: failure()
        uses: actions-cool/issues-helper@v3
        with:
          actions: 'create-issue'
          title: '🚨 同步失败 | Sync Fail'
          labels: '🚨 Sync Fail'
          body: |
            ## 同步失败详情 | Sync Failure Details

            **失败时间 | Failure Time:** ${{ steps.commit_info.outputs.sync_time || 'Unknown' }}
            **源仓库 | Source Repository:** [oiov/wr.do](https://github.com/oiov/wr.do)
            **目标分支 | Target Branch:** main
            **工作流运行 | Workflow Run:** [${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})

            ### 可能的原因 | Possible Causes:
            - 上游仓库的 workflow 文件发生变更
            - 存在合并冲突
            - 网络连接问题
            - 权限不足

            ### 解决方案 | Solutions:
            1. 手动执行 Sync Fork 操作
            2. 检查是否存在合并冲突
            3. 重新运行此工作流

            ---
            Due to a change in the workflow file of the [oiov/wr.do](https://github.com/oiov/wr.do) upstream repository, GitHub has automatically suspended the scheduled automatic update. You need to manually sync your fork.

            由于 [oiov/wr.do](https://github.com/oiov/wr.do) 上游仓库的 workflow 文件变更，导致 GitHub 自动暂停了本次自动更新，你需要手动 Sync Fork 一次。

