name: Build Desktop Launcher

on:
  push:
    tags:
      - "v*"
  workflow_dispatch:
    inputs:
      version:
        description: "Version label for binaries (e.g. v0.4.2)"
        required: false
        default: "dev"

permissions:
  contents: write

jobs:
  build:
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: macos-latest
            platform: macOS-arm64
          - os: macos-15-intel
            platform: macOS-x64
          - os: windows-latest
            platform: Windows

    name: Build ${{ matrix.platform }}
    runs-on: ${{ matrix.os }}
    env:
      BUILD_VERSION: ${{ github.event.inputs.version || github.ref_name || 'dev' }}

    steps:
      - uses: actions/checkout@v4

      - name: Set up Python 3.12
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - name: Install build dependencies
        run: pip install pyinstaller pystray Pillow

      - name: Import signing certificate (macOS)
        if: runner.os == 'macOS' && env.MACOS_SIGNING_CERT_BASE64 != ''
        env:
          MACOS_SIGNING_CERT_BASE64: ${{ secrets.MACOS_SIGNING_CERT_BASE64 }}
          MACOS_SIGNING_CERT_PASSWORD: ${{ secrets.MACOS_SIGNING_CERT_PASSWORD }}
        run: |
          CERT_FILE=$(mktemp /tmp/cert.XXXXXX.p12)
          echo "$MACOS_SIGNING_CERT_BASE64" | base64 --decode > "$CERT_FILE"
          KEYCHAIN="build.keychain"
          security create-keychain -p "" "$KEYCHAIN"
          security default-keychain -s "$KEYCHAIN"
          security unlock-keychain -p "" "$KEYCHAIN"
          security import "$CERT_FILE" -k "$KEYCHAIN" -P "$MACOS_SIGNING_CERT_PASSWORD" -T /usr/bin/codesign
          security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "" "$KEYCHAIN"
          rm -f "$CERT_FILE"

      - name: Generate platform icons
        run: python installer/launcher/build-launcher/make_icons.py

      - name: Build launcher
        run: python installer/launcher/build-launcher/build.py --version "${{ env.BUILD_VERSION }}"
        env:
          MACOS_SIGNING_IDENTITY: ${{ secrets.MACOS_SIGNING_IDENTITY || '-' }}
          MUDABBIR_VERSION: ${{ env.BUILD_VERSION }}

      - name: Create installer (Windows fallback)
        if: runner.os == 'Windows'
        run: |
          if (-not (Test-Path "dist\launcher\Mudabbir-Setup.exe")) {
            $issPath = "installer\launcher\build-launcher\mudabbir.iss"
            if (Test-Path $issPath) {
              & "C:\Program Files (x86)\Inno Setup 6\ISCC.exe" "/DVERSION=${{ env.BUILD_VERSION }}" $issPath
            }
          }
        shell: pwsh

      - name: Prepare release files (macOS)
        if: runner.os == 'macOS'
        run: |
          set -euo pipefail
          mkdir -p release
          if [ ! -f "dist/launcher/Mudabbir.dmg" ]; then
            echo "::error::DMG not found at dist/launcher/Mudabbir.dmg"
            exit 1
          fi
          OUT="Mudabbir-${{ matrix.platform }}.dmg"
          cp "dist/launcher/Mudabbir.dmg" "release/${OUT}"
          shasum -a 256 "release/${OUT}" > "release/${OUT}.sha256"
          ls -lh "release/${OUT}" "release/${OUT}.sha256"

      - name: Prepare release files (Windows)
        if: runner.os == 'Windows'
        run: |
          if (-not (Test-Path "dist\launcher\Mudabbir-Setup.exe")) {
            Write-Error "Installer not found at dist\launcher\Mudabbir-Setup.exe"
            exit 1
          }
          New-Item -ItemType Directory -Force -Path release | Out-Null
          Copy-Item "dist\launcher\Mudabbir-Setup.exe" "release\Mudabbir-Setup.exe"
          $hash = Get-FileHash "release\Mudabbir-Setup.exe" -Algorithm SHA256
          "$($hash.Hash)  Mudabbir-Setup.exe" | Out-File "release\Mudabbir-Setup.exe.sha256" -Encoding utf8
          Get-ChildItem release
        shell: pwsh

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

  publish-release:
    name: Publish GitHub Release Assets
    runs-on: ubuntu-latest
    needs: build
    if: startsWith(github.ref, 'refs/tags/v')

    steps:
      - name: Download built artifacts
        uses: actions/download-artifact@v4
        with:
          pattern: release-*
          path: release-assets
          merge-multiple: true

      - name: Show files
        run: ls -lah release-assets

      - name: Verify required release assets
        run: |
          set -euo pipefail
          required=(
            "Mudabbir-Setup.exe"
            "Mudabbir-Setup.exe.sha256"
            "Mudabbir-macOS-arm64.dmg"
            "Mudabbir-macOS-arm64.dmg.sha256"
            "Mudabbir-macOS-x64.dmg"
            "Mudabbir-macOS-x64.dmg.sha256"
          )
          missing=0
          for file in "${required[@]}"; do
            if [ ! -f "release-assets/${file}" ]; then
              echo "::error::Missing required release asset: ${file}"
              missing=1
            fi
          done
          if [ "$missing" -ne 0 ]; then
            exit 1
          fi

      - name: Create/Update release and upload files
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ github.ref_name }}
          name: Mudabbir ${{ github.ref_name }}
          generate_release_notes: true
          files: |
            release-assets/Mudabbir-Setup.exe
            release-assets/Mudabbir-Setup.exe.sha256
            release-assets/Mudabbir-macOS-arm64.dmg
            release-assets/Mudabbir-macOS-arm64.dmg.sha256
            release-assets/Mudabbir-macOS-x64.dmg
            release-assets/Mudabbir-macOS-x64.dmg.sha256
