name: Build & Release Desktop App

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

jobs:
  build:
    strategy:
      matrix:
        include:
          - platform: macos-latest
            target: universal-apple-darwin
          - platform: windows-latest
            target: x86_64-pc-windows-msvc

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

    steps:
      - name: Checkout Code
        uses: actions/checkout@v4

      # 设置 Python 环境（带 pip 缓存）
      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'
          cache: 'pip'
          cache-dependency-path: backend/requirements.txt

      # 安装 Python 依赖并执行构建
      - name: Install Python dependencies & Build backend
        shell: bash
        run: |
          python -m pip install --upgrade pip
          pip install -r backend/requirements.txt

          if [ "$RUNNER_OS" = "Windows" ]; then
            backend\\build.bat
          else
            chmod +x backend/build.sh
            ./backend/build.sh
          fi

      # 设置 pnpm
      # 不能用 'latest'：pnpm 11+ 要求 Node 22+，与下方 Node 20 不兼容（ERR_UNKNOWN_BUILTIN_MODULE）。
      # lockfile 是 pnpm 9 生成；统一 pin 到 9.15.0
      - name: Setup pnpm
        uses: pnpm/action-setup@v4
        with:
          version: '9.15.0'

      # 设置 Node 环境
      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install frontend dependencies
        working-directory: BillNote_frontend
        run: pnpm install

      # 设置 Rust 环境
      - name: Set up Rust
        uses: dtolnay/rust-toolchain@stable

      # Cargo 缓存
      - name: Cache Cargo
        uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/bin/
            ~/.cargo/registry/index/
            ~/.cargo/registry/cache/
            ~/.cargo/git/db/
            BillNote_frontend/src-tauri/target/
          key: ${{ runner.os }}-cargo-${{ hashFiles('BillNote_frontend/src-tauri/Cargo.lock') }}
          restore-keys: ${{ runner.os }}-cargo-

      # 从 tag 注入版本号到 tauri.conf.json：Tauri 取该文件的静态 version 作为
      # 产物版本，不同步的话构建产物会恒为 conf 里写死的值（此前的 2.0.0）。
      # github.ref_name 形如 v2.3.2，去掉前缀 v。workflow_dispatch（无 tag）时跳过，保留静态值。
      - name: Sync version from tag
        if: startsWith(github.ref, 'refs/tags/v')
        working-directory: BillNote_frontend
        shell: bash
        run: |
          VERSION="${GITHUB_REF_NAME#v}"
          echo "Injecting version $VERSION into tauri.conf.json"
          node -e "const f='src-tauri/tauri.conf.json'; const fs=require('fs'); const j=JSON.parse(fs.readFileSync(f,'utf8')); j.version=process.argv[1]; fs.writeFileSync(f, JSON.stringify(j,null,2)+'\n');" "$VERSION"
          node -e "console.log('tauri.conf.json version =', require('./src-tauri/tauri.conf.json').version)"

      # 打包 Tauri 应用
      - name: Build Tauri App
        working-directory: BillNote_frontend
        run: pnpm tauri build

      # 收集产物到统一目录
      - name: Collect release artifacts
        shell: bash
        run: |
          mkdir -p release-artifacts
          BUNDLE_DIR="BillNote_frontend/src-tauri/target/release/bundle"

          # macOS: .dmg
          find "$BUNDLE_DIR" -name "*.dmg" -exec cp {} release-artifacts/ \; 2>/dev/null || true
          # Windows: .msi, .exe (NSIS)
          find "$BUNDLE_DIR" -name "*.msi" -exec cp {} release-artifacts/ \; 2>/dev/null || true
          find "$BUNDLE_DIR/nsis" -name "*.exe" -exec cp {} release-artifacts/ \; 2>/dev/null || true

          echo "=== Collected artifacts ==="
          ls -lh release-artifacts/

      # 生成 SHA256 校验和
      - name: Generate checksums
        shell: bash
        run: |
          cd release-artifacts
          sha256sum * > SHA256SUMS.txt 2>/dev/null || shasum -a 256 * > SHA256SUMS.txt
          cat SHA256SUMS.txt

      # 上传产物（供 release job 使用）
      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: artifacts-${{ matrix.platform }}
          path: release-artifacts/

  # 创建 GitHub Release 并上传所有产物
  release:
    needs: build
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/v')
    permissions:
      contents: write

    steps:
      - name: Checkout Code
        uses: actions/checkout@v4

      # 下载所有平台的构建产物
      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: all-artifacts
          merge-multiple: true

      - name: List all artifacts
        run: |
          echo "=== All release artifacts ==="
          ls -lhR all-artifacts/

      # 创建 Release 并上传产物
      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          name: BiliNote ${{ github.ref_name }}
          draft: false
          prerelease: false
          generate_release_notes: true
          files: all-artifacts/*
