name: Build Electron

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

jobs:
  build:
    name: Build (${{ matrix.os }})
    runs-on: ${{ matrix.os }}
    timeout-minutes: 30
    permissions:
      contents: write
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: macos-latest
            platform: mac-arm64
            build_args: --mac --arm64
          - os: macos-latest
            platform: mac-x64
            build_args: --mac --x64
          - os: windows-latest
            platform: win
            build_args: --win
          - os: ubuntu-latest
            platform: linux
            build_args: --linux

    steps:
      - uses: actions/checkout@v4
        with:
          submodules: recursive

      - uses: oven-sh/setup-bun@v2
        with:
          bun-version: latest

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

      - uses: mlugg/setup-zig@v2
        with:
          version: 0.15.2

      - name: Install dependencies
        run: bun install --frozen-lockfile

      - name: Build web (electron target)
        run: bun --bun run build
        env:
          BUILD_TARGET: electron

      - name: Compile electron
        run: bun run electron:compile

      - name: Compile MCP server
        run: bun run mcp:compile

      - name: Checkout openpencil-skill
        uses: actions/checkout@v4
        with:
          repository: zseven-w/openpencil-skill
          path: external/openpencil-skill

      - name: Compile CLI
        env:
          SKILL_ROOT: ${{ github.workspace }}/external/openpencil-skill
        run: bun run cli:compile

      - name: Build Electron app
        run: npx electron-builder --config apps/desktop/electron-builder.yml ${{ matrix.build_args }} --publish never
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          CSC_LINK: ${{ secrets.CSC_LINK }}
          CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
          WIN_CSC_LINK: ${{ secrets.WIN_CSC_LINK }}
          WIN_CSC_KEY_PASSWORD: ${{ secrets.WIN_CSC_KEY_PASSWORD }}
          APPLE_ID: ${{ secrets.APPLE_ID }}
          APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
          APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}

      - name: Rename arm64 update metadata
        if: matrix.platform == 'mac-arm64'
        run: |
          if [ -f out/release/latest-mac.yml ]; then
            mv out/release/latest-mac.yml out/release/latest-mac-arm64.yml
          fi

      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: electron-${{ matrix.platform }}
          path: |
            out/release/*.dmg
            out/release/*.zip
            out/release/*.exe
            out/release/*.AppImage
            out/release/*.deb
            out/release/latest*.yml
            out/release/*.blockmap
            !out/release/builder-debug.yml
          retention-days: 30

  release:
    name: Create Release
    runs-on: ubuntu-latest
    needs: build
    if: startsWith(github.ref, 'refs/tags/v')
    permissions:
      contents: write

    steps:
      - uses: actions/checkout@v4

      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: artifacts/
          merge-multiple: true

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          draft: false
          generate_release_notes: true
          files: artifacts/*
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  update-homebrew:
    name: Update Homebrew Cask
    runs-on: ubuntu-latest
    needs: release
    if: startsWith(github.ref, 'refs/tags/v')

    steps:
      - name: Get version
        id: version
        run: echo "version=${GITHUB_REF#refs/tags/v}" >> "$GITHUB_OUTPUT"

      - name: Download macOS zips and compute sha256
        run: |
          VERSION=${{ steps.version.outputs.version }}
          curl -fSL "https://github.com/zseven-w/openpencil/releases/download/v${VERSION}/OpenPencil-${VERSION}-arm64-mac.zip" -o arm64.zip
          curl -fSL "https://github.com/zseven-w/openpencil/releases/download/v${VERSION}/OpenPencil-${VERSION}-x64-mac.zip" -o x64.zip
          echo "SHA_ARM64=$(sha256sum arm64.zip | cut -d' ' -f1)" >> "$GITHUB_ENV"
          echo "SHA_X64=$(sha256sum x64.zip | cut -d' ' -f1)" >> "$GITHUB_ENV"

      - name: Checkout tap repo
        uses: actions/checkout@v4
        with:
          repository: zseven-w/homebrew-openpencil
          token: ${{ secrets.TAP_GITHUB_TOKEN }}

      - name: Update cask formula
        run: |
          VERSION=${{ steps.version.outputs.version }}
          mkdir -p Casks
          cat > Casks/openpencil.rb << EOF
          cask "openpencil" do
            version "${VERSION}"

            on_arm do
              sha256 "${SHA_ARM64}"
              url "https://github.com/zseven-w/openpencil/releases/download/v#{version}/OpenPencil-#{version}-arm64-mac.zip"
            end
            on_intel do
              sha256 "${SHA_X64}"
              url "https://github.com/zseven-w/openpencil/releases/download/v#{version}/OpenPencil-#{version}-x64-mac.zip"
            end

            name "OpenPencil"
            desc "Open-source vector design tool"
            homepage "https://github.com/zseven-w/openpencil"

            app "OpenPencil.app"

            zap trash: [
              "~/Library/Application Support/OpenPencil",
              "~/Library/Preferences/dev.openpencil.app.plist",
              "~/Library/Caches/dev.openpencil.app",
            ]
          end
          EOF

      - name: Commit and push
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add Casks/openpencil.rb
          git diff --cached --quiet && exit 0
          git commit -m "Update OpenPencil to ${{ steps.version.outputs.version }}"
          git push

  update-scoop:
    name: Update Scoop Bucket
    runs-on: ubuntu-latest
    needs: release
    if: startsWith(github.ref, 'refs/tags/v')

    steps:
      - name: Get version
        id: version
        run: echo "version=${GITHUB_REF#refs/tags/v}" >> "$GITHUB_OUTPUT"

      - name: Download Windows portable and compute sha256
        run: |
          VERSION=${{ steps.version.outputs.version }}
          curl -fSL "https://github.com/zseven-w/openpencil/releases/download/v${VERSION}/OpenPencil-${VERSION}-x64-win.exe" -o win64.exe
          echo "SHA_WIN64=$(sha256sum win64.exe | cut -d' ' -f1)" >> "$GITHUB_ENV"

      - name: Checkout scoop bucket
        uses: actions/checkout@v4
        with:
          repository: zseven-w/scoop-openpencil
          token: ${{ secrets.TAP_GITHUB_TOKEN }}

      - name: Update manifest
        run: |
          VERSION=${{ steps.version.outputs.version }}
          mkdir -p bucket
          cat > bucket/openpencil.json << EOF
          {
            "version": "${VERSION}",
            "description": "Open-source AI-native vector design tool",
            "homepage": "https://github.com/zseven-w/openpencil",
            "license": "MIT",
            "architecture": {
              "64bit": {
                "url": "https://github.com/zseven-w/openpencil/releases/download/v${VERSION}/OpenPencil-${VERSION}-x64-win.exe",
                "hash": "${SHA_WIN64}"
              }
            },
            "pre_install": "Rename-Item \"\$dir\\OpenPencil-\$version-x64-win.exe\" 'OpenPencil.exe'",
            "bin": "OpenPencil.exe",
            "shortcuts": [["OpenPencil.exe", "OpenPencil"]],
            "checkver": {
              "github": "https://github.com/zseven-w/openpencil"
            },
            "autoupdate": {
              "architecture": {
                "64bit": {
                  "url": "https://github.com/zseven-w/openpencil/releases/download/v\$version/OpenPencil-\$version-x64-win.exe"
                }
              },
              "pre_install": "Rename-Item \"\$dir\\OpenPencil-\$version-x64-win.exe\" 'OpenPencil.exe'"
            }
          }
          EOF

      - name: Commit and push
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add bucket/openpencil.json
          git diff --cached --quiet && exit 0
          git commit -m "Update OpenPencil to ${{ steps.version.outputs.version }}"
          git push
