name: Release

on:
  push:
    tags:
      - 'v*'
  workflow_dispatch:

permissions:
  contents: write

jobs:
  build-linux-x86_64:
    name: Build Linux x86_64
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable

      - name: Cache cargo registry
        uses: actions/cache@v3
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
            target
          key: ${{ runner.os }}-x86_64-cargo-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: ${{ runner.os }}-x86_64-cargo-

      - name: Build release binary
        run: cargo build --release

      - name: Rename binary
        run: |
          mv target/release/mc-minder mc-minder-x86_64-linux
          chmod +x mc-minder-x86_64-linux

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: mc-minder-x86_64-linux
          path: mc-minder-x86_64-linux

  build-termux-aarch64:
    name: Build Termux ARM64
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: aarch64-linux-android

      - name: Cache cargo registry
        uses: actions/cache@v3
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
            target
          key: ${{ runner.os }}-aarch64-cargo-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: ${{ runner.os }}-aarch64-cargo-

      - name: Install cross via binstall
        run: |
          curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash
          cargo binstall -y cross

      - name: Build for Android ARM64
        run: cross build --target aarch64-linux-android --release

      - name: Rename binary
        run: |
          mv target/aarch64-linux-android/release/mc-minder mc-minder-termux-aarch64
          chmod +x mc-minder-termux-aarch64

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: mc-minder-termux-aarch64
          path: mc-minder-termux-aarch64

  release:
    needs: [build-linux-x86_64, build-termux-aarch64]
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: ./binaries

      - name: Get version from tag
        id: get_version
        run: echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT

      - name: Generate Changelog
        id: changelog
        run: |
          # 获取上一个 tag（如果有）
          PREVIOUS_TAG=$(git tag --sort=-version:refname | grep -v "${{ steps.get_version.outputs.VERSION }}" | head -1)
          
          if [ -n "$PREVIOUS_TAG" ]; then
            echo "Generating changelog from ${PREVIOUS_TAG} to ${{ steps.get_version.outputs.VERSION }}"
            RANGE="${PREVIOUS_TAG}..${{ steps.get_version.outputs.VERSION }}"
          else
            echo "No previous tag found, generating full changelog"
            RANGE=""
          fi
          
          # 按类型分类的 changelog
          FEAT=""
          FIX=""
          DOCS=""
          REFACTOR=""
          PERF=""
          TEST=""
          CHORE=""
          OTHER=""
          
          # 解析每个 commit（格式：hash|message）
          while IFS='|' read -r hash msg; do
            [ -z "$hash" ] && continue
            
            # 获取短 hash
            short_hash="${hash:0:7}"
            # 构建 commit 链接
            commit_link="([${short_hash}](https://github.com/${{ github.repository }}/commit/${hash}))"
            
            # 提取类型和消息
            if echo "$msg" | grep -qE '^feat(\(|:)'; then
              clean_msg=$(echo "$msg" | sed 's/^feat[^:]*: //')
              FEAT="${FEAT}\n- ${clean_msg} ${commit_link}"
            elif echo "$msg" | grep -qE '^fix(\(|:)'; then
              clean_msg=$(echo "$msg" | sed 's/^fix[^:]*: //')
              FIX="${FIX}\n- ${clean_msg} ${commit_link}"
            elif echo "$msg" | grep -qE '^docs(\(|:)'; then
              clean_msg=$(echo "$msg" | sed 's/^docs[^:]*: //')
              DOCS="${DOCS}\n- ${clean_msg} ${commit_link}"
            elif echo "$msg" | grep -qE '^refactor(\(|:)'; then
              clean_msg=$(echo "$msg" | sed 's/^refactor[^:]*: //')
              REFACTOR="${REFACTOR}\n- ${clean_msg} ${commit_link}"
            elif echo "$msg" | grep -qE '^perf(\(|:)'; then
              clean_msg=$(echo "$msg" | sed 's/^perf[^:]*: //')
              PERF="${PERF}\n- ${clean_msg} ${commit_link}"
            elif echo "$msg" | grep -qE '^test(\(|:)'; then
              clean_msg=$(echo "$msg" | sed 's/^test[^:]*: //')
              TEST="${TEST}\n- ${clean_msg} ${commit_link}"
            elif echo "$msg" | grep -qE '^chore(\(|:)'; then
              clean_msg=$(echo "$msg" | sed 's/^chore[^:]*: //')
              CHORE="${CHORE}\n- ${clean_msg} ${commit_link}"
            elif echo "$msg" | grep -qE '^ci(\(|:)'; then
              clean_msg=$(echo "$msg" | sed 's/^ci[^:]*: //')
              CHORE="${CHORE}\n- ${clean_msg} ${commit_link}"
            else
              OTHER="${OTHER}\n- ${msg} ${commit_link}"
            fi
          done <<< "$(git log $RANGE --pretty=format:'%H|%s' --no-merges)"
          
          # 构建最终 changelog
          CHANGELOG=""
          
          if [ -n "$FEAT" ]; then
            CHANGELOG="${CHANGELOG}\n### 新功能\n${FEAT}\n"
          fi
          
          if [ -n "$FIX" ]; then
            CHANGELOG="${CHANGELOG}\n### 问题修复\n${FIX}\n"
          fi
          
          if [ -n "$PERF" ]; then
            CHANGELOG="${CHANGELOG}\n### 性能优化\n${PERF}\n"
          fi
          
          if [ -n "$REFACTOR" ]; then
            CHANGELOG="${CHANGELOG}\n### 代码重构\n${REFACTOR}\n"
          fi
          
          if [ -n "$DOCS" ]; then
            CHANGELOG="${CHANGELOG}\n### 文档更新\n${DOCS}\n"
          fi
          
          if [ -n "$TEST" ]; then
            CHANGELOG="${CHANGELOG}\n### 测试\n${TEST}\n"
          fi
          
          if [ -n "$CHORE" ]; then
            CHANGELOG="${CHANGELOG}\n### 其他改动\n${CHORE}\n"
          fi
          
          if [ -n "$OTHER" ]; then
            CHANGELOG="${CHANGELOG}\n### 其他提交\n${OTHER}\n"
          fi
          
          # 如果没有内容，使用默认消息
          if [ -z "$CHANGELOG" ]; then
            CHANGELOG="### 初始发布"
          fi
          
          # 将 changelog 写入输出
          echo "changelog<<EOF" >> $GITHUB_OUTPUT
          echo -e "$CHANGELOG" >> $GITHUB_OUTPUT
          echo "EOF" >> $GITHUB_OUTPUT

      - name: Create Release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ steps.get_version.outputs.VERSION }}
          name: MC-Minder ${{ steps.get_version.outputs.VERSION }}
          body: |
            ## MC-Minder ${{ steps.get_version.outputs.VERSION }}
            
            ### 更新内容
            
            ${{ steps.changelog.outputs.changelog }}
            
            ---
            
            ### 下载
            
            | 平台 | 文件 | 说明 |
            |------|------|------|
            | Linux x64 | `mc-minder-x86_64-linux` | 适用于桌面 Linux / WSL |
            | Termux/Android ARM64 | `mc-minder-termux-aarch64` | 适用于手机 Termux 环境 |
            
            ### 安装
            
            ```bash
            curl -fsSL https://raw.githubusercontent.com/SharkMI-0x7E/mc-minder/main/install.sh | bash
            ```
          files: |
            binaries/mc-minder-x86_64-linux/mc-minder-x86_64-linux
            binaries/mc-minder-termux-aarch64/mc-minder-termux-aarch64
            install.sh
          draft: false
          prerelease: false
