name: Build Desktop App

on:
  workflow_dispatch:
    inputs:
      publish:
        description: 'Upload artifacts to GitHub Release'
        type: boolean
        default: false
  push:
    tags:
      - 'v*'

jobs:
  build:
    strategy:
      matrix:
        include:
          - os: macos-latest
            target: mac
            artifact: "desktop/dist/*.dmg"
          - os: windows-latest
            target: win
            artifact: "desktop/dist/*.exe"

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

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: '20'

      - uses: astral-sh/setup-uv@v5
        with:
          version: 'latest'

      # Build the Python venv that gets bundled into the app
      - name: Build Python venv
        shell: bash
        working-directory: desktop
        run: bash scripts/build-venv.sh

      - name: Install Node dependencies
        working-directory: desktop
        run: npm ci

      - name: Build app bundle (${{ matrix.target }})
        working-directory: desktop
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: npm run build:${{ matrix.target }}

      - name: Create DMG (macOS)
        if: matrix.target == 'mac'
        working-directory: desktop
        run: |
          brew install create-dmg fileicon
          npm run dmg

      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: distillate-${{ matrix.target }}
          path: ${{ matrix.artifact }}
          if-no-files-found: error

  release:
    needs: build
    if: startsWith(github.ref, 'refs/tags/v')
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/download-artifact@v4
        with:
          path: artifacts

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          files: artifacts/**/*
          draft: true
          generate_release_notes: true
