name: Release

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

jobs:
  publish:
    permissions:
      contents: write
    strategy:
      fail-fast: false
      matrix:
        include:
          - platform: windows-latest
            # Windows 打包 NSIS 安装包，便携版 zip 由构建后的步骤额外生成
            args: ''
          - platform: macos-latest
            args: '--target aarch64-apple-darwin'
          - platform: macos-latest
            args: '--target x86_64-apple-darwin'
          - platform: ubuntu-22.04
            args: ''
          - platform: ubuntu-22.04-arm
            # Linux ARM64（aarch64）：使用 GitHub 官方 ARM64 托管 runner 原生构建
            # （AppImage 工具链不支持 x86→arm64 交叉编译，公共仓库可直接用该 runner）
            args: ''

    runs-on: ${{ matrix.platform }}

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: lts/*
          cache: npm

      - name: Install Rust stable
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.platform == 'macos-latest' && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }}

      - name: Rust cache
        uses: swatinem/rust-cache@v2
        with:
          workspaces: './src-tauri -> target'

      - name: Install Linux dependencies
        if: matrix.platform == 'ubuntu-22.04' || matrix.platform == 'ubuntu-22.04-arm'
        run: |
          sudo apt-get update
          sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf libgtk-3-dev libdpkg-dev rpm

      - name: Install frontend dependencies
        run: npm ci

      - name: Generate release notes
        uses: orhun/git-cliff-action@v4
        with:
          config: cliff.toml
          # tag push: 直接取该 tag 到上一个 tag 的提交（--latest）
          # workflow_dispatch: 取上个 tag 到当前 HEAD 的未发布提交（--unreleased），
          # 避免生成上一版（旧 tag）的说明
          args: ${{ startsWith(github.ref, 'refs/tags/') && '--latest --strip all' || '--unreleased --strip all' }}
        env:
          OUTPUT: RELEASE_NOTES.md

      - name: Prepare release body
        id: notes
        shell: bash
        run: |
          VERSION=$(cat VERSION)
          {
            echo "RELEASE_BODY<<GITCLIFF_EOF"
            echo "# Tydora v$VERSION"
            echo ""
            if [ -s RELEASE_NOTES.md ]; then
              cat RELEASE_NOTES.md
            else
              echo "See the assets to download and install this version."
            fi
            echo "GITCLIFF_EOF"
          } >> "$GITHUB_OUTPUT"

      - uses: tauri-apps/tauri-action@v0
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
          TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
        with:
          tagName: v__VERSION__
          releaseName: 'Tydora v__VERSION__'
          releaseBody: ${{ steps.notes.outputs.RELEASE_BODY }}
          releaseDraft: true
          prerelease: false
          args: ${{ matrix.args }}

      # Windows: 额外生成便携版（免安装）zip，内容为 release 构建出的 Tydora.exe
      - name: Package Windows portable zip
        if: matrix.platform == 'windows-latest'
        shell: pwsh
        run: |
          $version = (Get-Content VERSION).Trim()
          $exe = 'src-tauri/target/release/Tydora.exe'
          if (-not (Test-Path $exe)) { throw "Release exe not found: $exe" }
          $outDir = 'src-tauri/target/release/bundle/portable'
          New-Item -ItemType Directory -Force -Path $outDir | Out-Null
          $zip = Join-Path $outDir "Tydora_${version}_x64_portable.zip"
          Compress-Archive -Path $exe -DestinationPath $zip -Force
          Get-Item $zip | Select-Object FullName, Length

      # Windows: 把便携版 zip 上传到本次 GitHub Release（tauri-action 已创建 draft release）
      - name: Upload Windows portable zip to release
        if: matrix.platform == 'windows-latest'
        shell: bash
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          gh release upload "v$(cat VERSION)" src-tauri/target/release/bundle/portable/*.zip --clobber
