name: Build release branch snapshot

on:
  workflow_dispatch: # 手动触发
  push:
    branches:
      - wanxiang

concurrency:
  group: release-branch
  cancel-in-progress: true

jobs:
  build-release:
    runs-on: ubuntu-22.04

    permissions:
      contents: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 2
      - name: Setup Python
        uses: actions/setup-python@v4
        with:
          python-version: "3.x"

      - name: Release build
        run: bash .github/workflows/scripts/release-build.sh

      # 1. 用 dist/ 里的产物拼出 snapshot 目录
      - name: Prepare snapshot tree from dist
        run: |
          set -euo pipefail

          rm -rf snapshot
          mkdir -p snapshot

          # 使用 dist/ 里的目录构建 snapshot
          if ls dist/rime-wanxiang-* 1> /dev/null 2>&1; then
            for d in dist/rime-wanxiang-*; do
              [ -d "$d" ] || continue
              name="$(basename "$d")"
              echo "Copying directory $d -> snapshot/$name"
              mkdir -p "snapshot/$name"
              cp -a "$d"/. "snapshot/$name"/
            done
          else
            echo "Error: no dist/rime-wanxiang-* directories found."
            exit 1
          fi

          echo "Snapshot tree after prepare:"
          ls -R snapshot || true

      # 2. 检查这次提交是否修改了 dicts 相关文件（控制 3/4/5 是否执行）
      - name: Check if dicts changed
        id: dicts_changed
        run: |
          set -euo pipefail

          # 手动触发（workflow_dispatch）直接视为「有变动」，强制跑
          if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
            echo "changed=true" >> "$GITHUB_OUTPUT"
            exit 0
          fi

          # 找到上一条提交（第一次提交可能没有 HEAD^，单独处理）
          if git rev-parse HEAD^ >/dev/null 2>&1; then
            RANGE="HEAD^ HEAD"
          else
            echo "Only one commit, treat as changed."
            echo "changed=true" >> "$GITHUB_OUTPUT"
            exit 0
          fi

          # 检查本次改动的文件里有没有命中 dicts 目录
          if git diff --name-only $RANGE | grep -E '(^dicts/|^rime-wanxiang-.*/dicts/)' >/dev/null 2>&1; then
            echo "dicts changed."
            echo "changed=true" >> "$GITHUB_OUTPUT"
          else
            echo "dicts not changed."
            echo "changed=false" >> "$GITHUB_OUTPUT"
          fi

      # 3. 从 dist 中打出每夜词库 zip（不套文件夹，只打 dicts/**）
      - name: Pack nightly dict zips
        if: steps.dicts_changed.outputs.changed == 'true'
        run: |
          set -euo pipefail

          mkdir -p dist

          pack_dict() {
            local src="$1"
            local zip_name="$2"
            if [[ -d "$src" ]]; then
              echo "Packing $src -> dist/${zip_name}"
              (cd "$src" && zip -r -q "../../${zip_name}" .)
            else
              echo "Warning: $src does not exist, skipped."
            fi
          }

          pack_dict "dist/rime-wanxiang-moqi-fuzhu/dicts"    "pro-moqi-fuzhu-dicts.zip"
          pack_dict "dist/rime-wanxiang-flypy-fuzhu/dicts"   "pro-flypy-fuzhu-dicts.zip"
          pack_dict "dist/rime-wanxiang-zrm-fuzhu/dicts"     "pro-zrm-fuzhu-dicts.zip"
          pack_dict "dist/rime-wanxiang-tiger-fuzhu/dicts"   "pro-tiger-fuzhu-dicts.zip"
          pack_dict "dist/rime-wanxiang-wubi-fuzhu/dicts"    "pro-wubi-fuzhu-dicts.zip"
          pack_dict "dist/rime-wanxiang-hanxin-fuzhu/dicts"  "pro-hanxin-fuzhu-dicts.zip"
          pack_dict "dist/rime-wanxiang-shouyou-fuzhu/dicts" "pro-shouyou-fuzhu-dicts.zip"
          pack_dict "dist/rime-wanxiang-base/dicts"          "base-dicts.zip"

          echo "Nightly dict zips in dist/:"
          ls -1 dist/*.zip || true

      # 4. 删除旧的 Nightly Release 和 Tag
      - name: Delete existing Nightly Release and Tag
        if: steps.dicts_changed.outputs.changed == 'true'
        uses: actions/github-script@v6
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            const tag = "dict-nightly";
            try {
              const releases = await github.rest.repos.listReleases({
                owner: context.repo.owner,
                repo: context.repo.repo
              });
              const existingRelease = releases.data.find(r => r.tag_name === tag);
              if (existingRelease) {
                console.log(`Deleting existing Release with ID: ${existingRelease.id}`);
                await github.rest.repos.deleteRelease({
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  release_id: existingRelease.id
                });
              }

              console.log(`Deleting tag: ${tag}`);
              await github.rest.git.deleteRef({
                owner: context.repo.owner,
                repo: context.repo.repo,
                ref: `tags/${tag}`
              });
            } catch (error) {
              console.log(`Error deleting Release or Tag: ${error.message}`);
            }

      - name: Wait for cleanup
        if: steps.dicts_changed.outputs.changed == 'true'
        run: sleep 10

      # 5. 创建新的 Nightly Release，上传词库 zips
      - name: Create dict-nightly Release
        if: steps.dicts_changed.outputs.changed == 'true'
        uses: softprops/action-gh-release@v2
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          tag_name: dict-nightly
          name: "实时提交的词库更新"
          body: |
            - **base-dicts.zip**：最新的标准版原始中文词库文件
            - **pro-moqi-fuzhu-dicts.zip**：携带了墨奇辅助码的词库文件
            - **pro-flypy-fuzhu-dicts.zip**：携带了小鹤辅助码的词库文件
            - **pro-zrm-fuzhu-dicts.zip**：携带了自然码辅助码的词库文件
            - **pro-tiger-fuzhu-dicts.zip**：携带了虎码辅助码的词库文件
            - **pro-wubi-fuzhu-dicts.zip**：携带了五笔辅助码的词库文件
            - **pro-hanxin-fuzhu-dicts.zip**：携带了汉心辅助码的词库文件
            - **pro-shouyou-fuzhu-dicts.zip**：携带了首右辅助码的词库文件
            - **[wanxiang-lts-zh-hans.gram](https://github.com/amzxyz/RIME-LMDG/releases/download/LTS/wanxiang-lts-zh-hans.gram)**：与词库同步更新的语法模型
          files: |
            dist/pro-moqi-fuzhu-dicts.zip
            dist/pro-flypy-fuzhu-dicts.zip
            dist/pro-zrm-fuzhu-dicts.zip
            dist/pro-tiger-fuzhu-dicts.zip
            dist/pro-wubi-fuzhu-dicts.zip
            dist/pro-hanxin-fuzhu-dicts.zip
            dist/pro-shouyou-fuzhu-dicts.zip
            dist/base-dicts.zip
          draft: false
          prerelease: false
          make_latest: true

      # 6. 为每个方案生成独立分支：wanxiang-base / wanxiang-moqi-fuzhu / ...
      - name: Commit and force push per-scheme snapshots
        env:
          GIT_AUTHOR_NAME: ci-bot
          GIT_AUTHOR_EMAIL: ci@example.com
          GIT_COMMITTER_NAME: ci-bot
          GIT_COMMITTER_EMAIL: ci@example.com
        run: |
          set -euo pipefail

          # 当前开发分支（通常是 wanxiang）
          ORIG_BRANCH="$(git rev-parse --abbrev-ref HEAD || echo 'wanxiang')"

          # 方案列表
          schemes=("base" "shouyou-fuzhu" "zrm-fuzhu" "tiger-fuzhu" "moqi-fuzhu" "flypy-fuzhu" "wubi-fuzhu" "hanxin-fuzhu")

          # 每个方案公共文件清单（在分支根目录使用）
          COMMON_FILES=(
            "dicts/*.*"
            "opencc/*.*"
            "custom/*.*"
            "lua/*.*"
            "lua/lib/*.*"
            "lua/tips/*.*"
            "default.yaml"
            "weasel.yaml"
            "wanxiang*.*yaml"
            "README.md"
            "简纯+.trime.yaml"
            "custom_phrase.txt"
          )

          TAG_NAME="${{ github.event_name == 'release' && github.event.release.tag_name || 'manual-build' }}"

          for scheme in "${schemes[@]}"; do
            branch="wanxiang-${scheme}"                   # 分支名：wanxiang-moqi-fuzhu
            src_dir="snapshot/rime-wanxiang-${scheme}"    # 每个方案的源码目录（来自 snapshot）

            echo "=== Building branch ${branch} from ${src_dir} ==="

            if [ ! -d "${src_dir}" ]; then
              echo "Warning: ${src_dir} not found, skip ${branch}."
              continue
            fi

            # 切换/创建分支
            if git show-ref --verify --quiet "refs/heads/${branch}"; then
              git checkout "${branch}"
            else
              git checkout --orphan "${branch}"
            fi

            # 清空当前工作区（仅保留 .git 和 snapshot）
            find . -mindepth 1 -maxdepth 1 ! -name ".git" ! -name "snapshot" -exec rm -rf {} +

            # 把这个方案的内容「拍扁」到分支根目录（不保留 rime-wanxiang-xxx 那一层）
            cp -a "${src_dir}"/. .

            # 在这个分支里生成自己的 plum 配方
            mkdir -p plum

            #################################
            # 生成 plum/full.recipe.yaml
            #################################
            {
              echo "# encoding: utf-8"
              echo "---"
              echo "recipe:"
              echo "  Rx: plum/full"
              echo "  args:"
              echo "  description: >-"
              echo "    万象拼音 ${scheme} 版（整个方案目录）- 分支 ${branch}"
              echo "install_files: >-"
              for path in "${COMMON_FILES[@]}"; do
                echo "  ${path}"
              done
            } > "plum/full.recipe.yaml"

            #################################
            # 生成 plum/dicts.recipe.yaml
            #################################
            {
              echo "# encoding: utf-8"
              echo "---"
              echo "recipe:"
              echo "  Rx: plum/dicts"
              echo "  args:"
              echo "  description: >-"
              echo "    万象拼音 ${scheme} 版，仅词库（dicts-only）- 分支 ${branch}"
              echo "install_files: >-"
              echo "  dicts/*.*"
            } > "plum/dicts.recipe.yaml"

            git status

            # 注意：不要把 snapshot/ 提交进去
            git add .
            git reset snapshot || true
            git rm -r --cached snapshot 2>/dev/null || true

            git commit -m "chore(${branch}): snapshot for ${TAG_NAME}" \
              || echo "Nothing to commit for ${branch}."

            git push -f origin "${branch}"
          done

          # 回到原来的开发分支，并清掉 snapshot（只删 CI 本地）
          git checkout "${ORIG_BRANCH}" || true
          rm -rf snapshot
