name: Release

on:
  push:
    tags: ['v*']

permissions:
  contents: write

jobs:
  build:
    strategy:
      fail-fast: false
      matrix:
        include:
          - platform: macos-latest
            target: aarch64-apple-darwin
            label: macOS-ARM64
          - platform: macos-latest
            target: x86_64-apple-darwin
            label: macOS-x64
          - platform: ubuntu-22.04
            target: x86_64-unknown-linux-gnu
            label: Linux-x64
          - platform: windows-latest
            target: x86_64-pc-windows-msvc
            label: Windows-x64

    runs-on: ${{ matrix.platform }}
    name: Build (${{ matrix.label }})

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

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

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - name: Rust cache
        uses: swatinem/rust-cache@v2
        with:
          workspaces: src-tauri

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

      - name: Import Apple certificate (macOS only)
        if: contains(matrix.target, 'apple-darwin')
        env:
          APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
          APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
        run: |
          CERTIFICATE_PATH=$RUNNER_TEMP/certificate.p12
          KEYCHAIN_PATH=$RUNNER_TEMP/app-signing.keychain-db
          KEYCHAIN_PASSWORD=$(openssl rand -base64 32)

          # Decode certificate
          echo "$APPLE_CERTIFICATE" | base64 --decode > "$CERTIFICATE_PATH"

          # Create temporary keychain
          security create-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
          security set-keychain-settings -lut 21600 "$KEYCHAIN_PATH"
          security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"

          # Import certificate
          security import "$CERTIFICATE_PATH" -P "$APPLE_CERTIFICATE_PASSWORD" \
            -A -t cert -f pkcs12 -k "$KEYCHAIN_PATH"
          security set-key-partition-list -S apple-tool:,apple: \
            -k "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
          security list-keychain -d user -s "$KEYCHAIN_PATH" login.keychain

          # Clean up certificate file
          rm "$CERTIFICATE_PATH"

      - name: Write Apple API key (macOS only)
        if: contains(matrix.target, 'apple-darwin')
        env:
          APPLE_API_KEY_CONTENT: ${{ secrets.APPLE_API_KEY_CONTENT }}
        run: |
          mkdir -p ~/.private_keys
          echo "$APPLE_API_KEY_CONTENT" > ~/.private_keys/AuthKey_${{ secrets.APPLE_API_KEY }}.p8

      - name: Install frontend dependencies
        run: npm ci

      - name: Build Tauri app
        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 }}
          APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
          APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
          APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
          APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
          APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
          APPLE_API_KEY_PATH: ~/.private_keys/AuthKey_${{ secrets.APPLE_API_KEY }}.p8
        with:
          tagName: ${{ github.ref_name }}
          releaseName: ClawPal ${{ github.ref_name }}
          releaseBody: |
            ## ClawPal ${{ github.ref_name }}

            ### Installation

            **macOS**:
            - Download the `.dmg` for your architecture (ARM for Apple Silicon, x64 for Intel)
            - Open the DMG and drag ClawPal to Applications

            **Windows** (unsigned — SmartScreen will warn):
            - **Portable**: Download `ClawPal_portable_x64.exe` — no install needed (requires WebView2)
            - **Installer**: Download the NSIS `.exe` or `.msi`
            - If SmartScreen blocks: click "More info" → "Run anyway"

            **Linux**:
            - `.deb`: `sudo dpkg -i clawpal_*.deb`
            - `.AppImage`: `chmod +x ClawPal_*.AppImage && ./ClawPal_*.AppImage`
          releaseDraft: true
          prerelease: false
          args: --target ${{ matrix.target }}

      - name: Upload Windows portable exe
        if: matrix.platform == 'windows-latest'
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        shell: pwsh
        run: |
          $exe = Get-ChildItem "src-tauri/target/${{ matrix.target }}/release/clawpal.exe" -ErrorAction SilentlyContinue
          if ($exe) {
            $dest = "ClawPal_portable_x64.exe"
            Copy-Item $exe.FullName $dest
            gh release upload ${{ github.ref_name }} $dest --clobber
          }

      - name: Cleanup Apple signing (macOS only)
        if: ${{ contains(matrix.target, 'apple-darwin') && always() }}
        run: |
          security delete-keychain $RUNNER_TEMP/app-signing.keychain-db 2>/dev/null || true
          rm -f ~/.private_keys/AuthKey_*.p8 2>/dev/null || true
