name: Release

on:
  push:
    tags:
      - "app-v*"
  workflow_dispatch:
    inputs:
      platforms:
        description: "Platforms to build (comma-separated: linux,windows,macos)"
        required: false
        default: "linux,windows,macos"
      version:
        description: "Version override (e.g., 1.2.0)"
        required: false
      publish:
        description: "Publish GitHub release"
        required: false
        type: boolean
        default: true

env:
  CARGO_INCREMENTAL: 0

jobs:
  build-linux:
    name: Build Linux
    runs-on: ubuntu-22.04
    if: >-
      github.event_name == 'push' ||
      contains(github.event.inputs.platforms, 'linux')
    timeout-minutes: 25
    steps:
      - uses: actions/checkout@v6

      - name: Install Linux dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y \
            libwebkit2gtk-4.1-dev \
            libappindicator3-dev \
            librsvg2-dev \
            patchelf \
            libssl-dev \
            clang \
            lld \
            rpm

      - uses: oven-sh/setup-bun@v2

      - uses: dtolnay/rust-toolchain@stable

      - uses: swatinem/rust-cache@v2

      - name: Install frontend dependencies
        working-directory: web
        run: bun install

      - name: Build frontend
        working-directory: web
        run: bun run build

      - name: Build desktop (deb, rpm, appimage)
        uses: tauri-apps/tauri-action@v0
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          APPIMAGE_EXTRACT_AND_RUN: "1"
        with:
          projectPath: crates/mesoclaw-desktop
          args: --bundles deb,rpm,appimage -- --profile ci-release

      - name: Build standalone CLI and daemon
        run: cargo build --profile ci-release -p mesoclaw-cli -p mesoclaw-daemon -p mesoclaw-tui --features keyring,channels,channels-telegram,channels-slack,channels-discord,scheduler,web-dashboard

      - name: Rename standalone binaries with platform label
        run: |
          cp target/ci-release/mesoclaw target/ci-release/mesoclaw-linux
          cp target/ci-release/mesoclaw-daemon target/ci-release/mesoclaw-daemon-linux
          cp target/ci-release/mesoclaw-tui target/ci-release/mesoclaw-tui-linux

      - name: Upload desktop artifacts
        uses: actions/upload-artifact@v7
        with:
          name: linux-desktop
          path: |
            target/ci-release/bundle/deb/*.deb
            target/ci-release/bundle/rpm/*.rpm
            target/ci-release/bundle/appimage/*.AppImage

      - name: Upload standalone binaries
        uses: actions/upload-artifact@v7
        with:
          name: linux-standalone
          path: |
            target/ci-release/mesoclaw-linux
            target/ci-release/mesoclaw-daemon-linux
            target/ci-release/mesoclaw-tui-linux

  build-windows:
    name: Build Windows
    runs-on: windows-latest
    if: >-
      github.event_name == 'push' ||
      contains(github.event.inputs.platforms, 'windows')
    timeout-minutes: 45
    steps:
      - uses: actions/checkout@v6

      - uses: oven-sh/setup-bun@v2

      - uses: dtolnay/rust-toolchain@stable

      - uses: swatinem/rust-cache@v2

      - name: Install frontend dependencies
        working-directory: web
        run: bun install

      - name: Build frontend
        working-directory: web
        run: bun run build

      - name: Build desktop (msi, nsis)
        uses: tauri-apps/tauri-action@v0
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          projectPath: crates/mesoclaw-desktop
          args: --bundles msi,nsis -- --profile ci-release

      - name: Build standalone CLI and daemon
        run: cargo build --profile ci-release -p mesoclaw-cli -p mesoclaw-daemon -p mesoclaw-tui --features keyring,channels,channels-telegram,channels-slack,channels-discord,scheduler,web-dashboard

      - name: Upload desktop artifacts
        uses: actions/upload-artifact@v7
        with:
          name: windows-desktop
          path: |
            target/ci-release/bundle/msi/*.msi
            target/ci-release/bundle/nsis/*.exe

      - name: Upload standalone binaries
        uses: actions/upload-artifact@v7
        with:
          name: windows-standalone
          path: |
            target/ci-release/mesoclaw.exe
            target/ci-release/mesoclaw-daemon.exe
            target/ci-release/mesoclaw-tui.exe

  build-macos:
    name: Build macOS
    runs-on: macos-latest
    if: >-
      github.event_name == 'push' ||
      contains(github.event.inputs.platforms, 'macos')
    timeout-minutes: 30
    steps:
      - uses: actions/checkout@v6

      - uses: oven-sh/setup-bun@v2

      - uses: dtolnay/rust-toolchain@stable
        with:
          targets: aarch64-apple-darwin,x86_64-apple-darwin

      - uses: swatinem/rust-cache@v2

      - name: Install frontend dependencies
        working-directory: web
        run: bun install

      - name: Build frontend
        working-directory: web
        run: bun run build

      - name: Import Apple certificate
        env:
          APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
          APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
          KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
        run: |
          CERTIFICATE_PATH=$RUNNER_TEMP/build_certificate.p12
          KEYCHAIN_PATH=$RUNNER_TEMP/app-signing.keychain-db

          echo -n "$APPLE_CERTIFICATE" | base64 --decode -o $CERTIFICATE_PATH

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

          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

      - name: Build desktop (dmg) - aarch64
        uses: tauri-apps/tauri-action@v0
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
          APPLE_ID: ${{ secrets.APPLE_ID }}
          APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
          APPLE_TEAM_ID: "6BQSGY2B74"
        with:
          projectPath: crates/mesoclaw-desktop
          args: --target aarch64-apple-darwin --bundles dmg -- --profile ci-release

      - name: Build desktop (dmg) - x86_64
        uses: tauri-apps/tauri-action@v0
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
          APPLE_ID: ${{ secrets.APPLE_ID }}
          APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
          APPLE_TEAM_ID: "6BQSGY2B74"
        with:
          projectPath: crates/mesoclaw-desktop
          args: --target x86_64-apple-darwin --bundles dmg -- --profile ci-release

      - name: Build standalone CLI and daemon (universal)
        run: |
          cargo build --profile ci-release -p mesoclaw-cli -p mesoclaw-daemon -p mesoclaw-tui --features keyring,channels,channels-telegram,channels-slack,channels-discord,scheduler,web-dashboard --target aarch64-apple-darwin
          cargo build --profile ci-release -p mesoclaw-cli -p mesoclaw-daemon -p mesoclaw-tui --features keyring,channels,channels-telegram,channels-slack,channels-discord,scheduler,web-dashboard --target x86_64-apple-darwin
          mkdir -p target/ci-release/universal
          lipo -create \
            target/aarch64-apple-darwin/ci-release/mesoclaw \
            target/x86_64-apple-darwin/ci-release/mesoclaw \
            -output target/ci-release/universal/mesoclaw
          lipo -create \
            target/aarch64-apple-darwin/ci-release/mesoclaw-daemon \
            target/x86_64-apple-darwin/ci-release/mesoclaw-daemon \
            -output target/ci-release/universal/mesoclaw-daemon
          lipo -create \
            target/aarch64-apple-darwin/ci-release/mesoclaw-tui \
            target/x86_64-apple-darwin/ci-release/mesoclaw-tui \
            -output target/ci-release/universal/mesoclaw-tui

      - name: Upload desktop artifacts
        uses: actions/upload-artifact@v7
        with:
          name: macos-desktop
          path: |
            target/aarch64-apple-darwin/ci-release/bundle/dmg/*.dmg
            target/x86_64-apple-darwin/ci-release/bundle/dmg/*.dmg

      - name: Rename standalone binaries with platform label
        run: |
          cp target/ci-release/universal/mesoclaw target/ci-release/universal/mesoclaw-macos
          cp target/ci-release/universal/mesoclaw-daemon target/ci-release/universal/mesoclaw-daemon-macos
          cp target/ci-release/universal/mesoclaw-tui target/ci-release/universal/mesoclaw-tui-macos

      - name: Upload standalone binaries
        uses: actions/upload-artifact@v7
        with:
          name: macos-standalone
          path: |
            target/ci-release/universal/mesoclaw-macos
            target/ci-release/universal/mesoclaw-daemon-macos
            target/ci-release/universal/mesoclaw-tui-macos

      - name: Cleanup keychain
        if: always()
        run: |
          KEYCHAIN_PATH=$RUNNER_TEMP/app-signing.keychain-db
          if [ -f "$KEYCHAIN_PATH" ]; then
            security delete-keychain $KEYCHAIN_PATH
          fi

  build-embedded:
    name: Build Embedded (${{ matrix.target }})
    runs-on: ubuntu-22.04
    if: >-
      github.event_name == 'push' ||
      contains(github.event.inputs.platforms, 'linux')
    timeout-minutes: 30
    strategy:
      fail-fast: false
      matrix:
        include:
          - target: aarch64-unknown-linux-gnu
            label: arm64
            extra-features: ""
          - target: armv7-unknown-linux-gnueabihf
            label: armv7
            extra-features: ""
          # TODO: musl needs vendored OpenSSL — re-enable after fixing cross-compilation
          # - target: x86_64-unknown-linux-musl
          #   label: musl
          #   extra-features: ",vendored-openssl"
    steps:
      - uses: actions/checkout@v6

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

      - uses: swatinem/rust-cache@v2
        with:
          key: ${{ matrix.target }}

      - name: Install cross-compilation tools
        run: cargo install cross --git https://github.com/cross-rs/cross

      - name: Build CLI, daemon, and TUI
        run: cross build --profile ci-release -p mesoclaw-cli -p mesoclaw-daemon -p mesoclaw-tui --no-default-features --features channels,channels-telegram,channels-slack,channels-discord,scheduler,web-dashboard${{ matrix.extra-features }} --target ${{ matrix.target }}

      - name: Rename binaries with target label
        run: |
          mkdir -p target/${{ matrix.target }}/ci-release/labeled
          cp target/${{ matrix.target }}/ci-release/mesoclaw target/${{ matrix.target }}/ci-release/labeled/mesoclaw-${{ matrix.label }}
          cp target/${{ matrix.target }}/ci-release/mesoclaw-daemon target/${{ matrix.target }}/ci-release/labeled/mesoclaw-daemon-${{ matrix.label }}
          cp target/${{ matrix.target }}/ci-release/mesoclaw-tui target/${{ matrix.target }}/ci-release/labeled/mesoclaw-tui-${{ matrix.label }}

      - name: Upload binaries
        uses: actions/upload-artifact@v7
        with:
          name: embedded-${{ matrix.label }}
          path: |
            target/${{ matrix.target }}/ci-release/labeled/mesoclaw-${{ matrix.label }}
            target/${{ matrix.target }}/ci-release/labeled/mesoclaw-daemon-${{ matrix.label }}
            target/${{ matrix.target }}/ci-release/labeled/mesoclaw-tui-${{ matrix.label }}

  # build-docker:
  #   name: Build & Push Docker Image
  #   runs-on: ubuntu-22.04
  #   needs: [build-linux]
  #   if: >-
  #     always() &&
  #     needs.build-linux.result == 'success' &&
  #     (startsWith(github.ref, 'refs/tags/app-v') ||
  #     (github.event_name == 'workflow_dispatch' && github.event.inputs.publish == 'true'))
  #   permissions:
  #     packages: write
  #   steps:
  #     - uses: actions/checkout@v6
  #
  #     - name: Set up Docker Buildx
  #       uses: docker/setup-buildx-action@v3
  #
  #     - name: Log in to GitHub Container Registry
  #       uses: docker/login-action@v3
  #       with:
  #         registry: ghcr.io
  #         username: ${{ github.actor }}
  #         password: ${{ secrets.GITHUB_TOKEN }}
  #
  #     - name: Extract metadata (tags, labels)
  #       id: meta
  #       uses: docker/metadata-action@v5
  #       with:
  #         images: ghcr.io/sprklai/mesoclaw
  #         tags: |
  #           type=semver,pattern={{version}},prefix=,value=${{ github.ref_name }}
  #           type=raw,value=latest
  #
  #     - name: Build and push multi-arch image
  #       uses: docker/build-push-action@v6
  #       with:
  #         context: .
  #         platforms: linux/amd64,linux/arm64
  #         push: true
  #         tags: ${{ steps.meta.outputs.tags }}
  #         labels: ${{ steps.meta.outputs.labels }}
  #         cache-from: type=gha
  #         cache-to: type=gha,mode=max

  release:
    name: Create Release
    runs-on: ubuntu-latest
    needs: [build-linux, build-windows, build-macos, build-embedded]
    if: >-
      always() &&
      needs.build-linux.result == 'success' &&
      (startsWith(github.ref, 'refs/tags/app-v') ||
      (github.event_name == 'workflow_dispatch' && github.event.inputs.publish == 'true'))
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v6

      - name: Download all artifacts
        uses: actions/download-artifact@v8
        with:
          path: artifacts

      - name: Generate checksums
        run: |
          cd artifacts
          find . -type f \( -name "*.deb" -o -name "*.rpm" -o -name "*.AppImage" \
            -o -name "*.dmg" -o -name "*.msi" -o -name "*.exe" \
            -o -name "mesoclaw-linux" -o -name "mesoclaw-daemon-linux" -o -name "mesoclaw-tui-linux" \
            -o -name "mesoclaw-macos" -o -name "mesoclaw-daemon-macos" -o -name "mesoclaw-tui-macos" \
            -o -name "mesoclaw-arm64" -o -name "mesoclaw-daemon-arm64" \
            -o -name "mesoclaw-armv7" -o -name "mesoclaw-daemon-armv7" \
            -o -name "mesoclaw.exe" -o -name "mesoclaw-daemon.exe" -o -name "mesoclaw-tui.exe" \) \
            -exec sha256sum {} \; > ../SHA256SUMS.txt
          cat ../SHA256SUMS.txt

      - name: Extract version from tag
        id: version
        env:
          INPUT_VERSION: ${{ github.event.inputs.version }}
          EVENT_NAME: ${{ github.event_name }}
        run: |
          if [ "$EVENT_NAME" = "workflow_dispatch" ] && [ -n "$INPUT_VERSION" ]; then
            echo "version=$INPUT_VERSION" >> "$GITHUB_OUTPUT"
          else
            echo "version=${GITHUB_REF#refs/tags/app-v}" >> "$GITHUB_OUTPUT"
          fi

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          name: MesoClaw v${{ steps.version.outputs.version }}
          generate_release_notes: true
          files: |
            artifacts/**/*.deb
            artifacts/**/*.rpm
            artifacts/**/*.AppImage
            artifacts/**/*.dmg
            artifacts/**/*.msi
            artifacts/**/*.exe
            artifacts/**/mesoclaw-linux
            artifacts/**/mesoclaw-daemon-linux
            artifacts/**/mesoclaw-tui-linux
            artifacts/**/mesoclaw-macos
            artifacts/**/mesoclaw-daemon-macos
            artifacts/**/mesoclaw-tui-macos
            artifacts/**/mesoclaw-arm64
            artifacts/**/mesoclaw-daemon-arm64
            artifacts/**/mesoclaw-armv7
            artifacts/**/mesoclaw-daemon-armv7
            SHA256SUMS.txt
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
