name: Build Gallery

# Build Gallery standalone executable workflow (FullStack mode with Python backend)
# Only runs on workflow_call (from release.yml) or manual trigger.
# Requires pre-built auroraview wheels for Python dependency collection.

on:
  workflow_dispatch:
  workflow_call:

permissions:
  contents: read
  actions: write

env:
  CARGO_TERM_COLOR: always
  RUST_BACKTRACE: 1

jobs:
  # First, build SDK assets (needed for wheel builds)
  build-sdk-assets:
    name: Build SDK Assets
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v6

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

      - name: Install SDK dependencies
        run: |
          cd packages/auroraview-sdk
          rm -rf node_modules package-lock.json
          npm install

      - name: Build SDK assets
        run: |
          cd packages/auroraview-sdk
          npm run build:assets

      - name: Upload SDK assets artifact
        uses: actions/upload-artifact@v6
        with:
          # Use unique name with run_id to avoid conflicts with other workflows
          name: gallery-sdk-assets-${{ github.run_id }}
          path: |
            crates/auroraview-core/src/assets/js/core/
            crates/auroraview-core/src/assets/js/plugins/
          retention-days: 7

  # Build wheels for all platforms (needed for Python dependency collection)
  build-wheels:
    name: Build Wheel (${{ matrix.os }})
    runs-on: ${{ matrix.os }}
    timeout-minutes: 25
    needs: build-sdk-assets
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64
            artifact-name: gallery-wheels-linux-x86_64
            maturin-args: '--release --out dist --find-interpreter --features python-bindings,ext-module,abi3-py38'
          - os: windows-latest
            target: x64
            artifact-name: gallery-wheels-windows-x64
            maturin-args: '--release --out dist --find-interpreter --features python-bindings,ext-module,abi3-py38,win-webview2'
          - os: macos-latest
            target: universal2-apple-darwin
            artifact-name: gallery-wheels-macos-universal2-apple-darwin
            maturin-args: '--release --out dist --find-interpreter --features python-bindings,ext-module,abi3-py38'
    steps:
      - uses: actions/checkout@v6

      - name: Download SDK assets
        uses: actions/download-artifact@v7
        with:
          name: gallery-sdk-assets-${{ github.run_id }}
          path: crates/auroraview-core/src/assets/js/

      - name: Build Wheel
        uses: ./.github/actions/build-wheel
        with:
          target: ${{ matrix.target }}
          python-version: '3.11'
          maturin-args: ${{ matrix.maturin-args }}
          test-wheel: 'false'
          artifact-name: ${{ matrix.artifact-name }}

  build:
    name: Build Gallery (${{ matrix.target }})
    runs-on: ${{ matrix.os }}
    needs: build-wheels
    strategy:
      fail-fast: false
      matrix:
        include:
          # Windows
          - os: windows-latest
            target: x86_64-pc-windows-msvc
            artifact: auroraview-gallery.exe
            archive: auroraview-gallery-windows-x64.zip
            wheel-artifact: gallery-wheels-windows-x64
          # macOS ARM
          - os: macos-latest
            target: aarch64-apple-darwin
            artifact: auroraview-gallery
            archive: auroraview-gallery-macos-arm64.tar.gz
            wheel-artifact: gallery-wheels-macos-universal2-apple-darwin
          # macOS Intel (cross-compile on ARM runner)
          - os: macos-latest
            target: x86_64-apple-darwin
            artifact: auroraview-gallery
            archive: auroraview-gallery-macos-x64.tar.gz
            wheel-artifact: gallery-wheels-macos-universal2-apple-darwin
          # Linux
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
            artifact: auroraview-gallery
            archive: auroraview-gallery-linux-x64.tar.gz
            wheel-artifact: gallery-wheels-linux-x86_64

    steps:
      - uses: actions/checkout@v6

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
          cache-dependency-path: gallery/package-lock.json

      - name: Setup Python
        uses: actions/setup-python@v6
        with:
          python-version: '3.11'

      - name: Download pre-built auroraview wheel
        uses: actions/download-artifact@v7
        with:
          name: ${{ matrix.wheel-artifact }}
          path: dist/

      - name: Install auroraview wheel
        shell: bash
        run: |
          python -m pip install --upgrade pip
          pip install dist/*.whl
          python -c "import auroraview; print(f'auroraview {auroraview.__version__} installed')"

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

      - name: Install Linux dependencies
        if: runner.os == 'Linux'
        run: |
          sudo apt-get update
          sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev libxdo-dev

      - name: Build SDK first (Gallery depends on it)
        shell: bash
        run: |
          cd packages/auroraview-sdk
          rm -rf node_modules package-lock.json
          npm install
          npm run build

      - name: Build Gallery frontend
        shell: bash
        run: |
          cd gallery
          # Retry npm ci up to 3 times to handle transient network errors
          for i in 1 2 3; do
            echo "Attempt $i: Running npm ci..."
            if npm ci; then
              echo "npm ci succeeded on attempt $i"
              break
            else
              if [ $i -eq 3 ]; then
                echo "npm ci failed after 3 attempts"
                exit 1
              fi
              echo "npm ci failed, waiting 10 seconds before retry..."
              sleep 10
            fi
          done
          npm run build

      - name: Build CLI (for pack command)
        run: cargo build -p auroraview-cli --release --target ${{ matrix.target }}

      - name: Pack Gallery executable (FullStack mode)
        shell: bash
        run: |
          mkdir -p target/pack
          if [[ "${{ runner.os }}" == "Windows" ]]; then
            ./target/${{ matrix.target }}/release/auroraview-cli.exe pack \
              --config gallery/auroraview.pack.toml \
              --output-dir target/pack
          else
            ./target/${{ matrix.target }}/release/auroraview-cli pack \
              --config gallery/auroraview.pack.toml \
              --output-dir target/pack
          fi

      - name: Verify pack output
        shell: bash
        run: |
          echo "Pack output:"
          ls -la target/pack/
          # Verify executable exists
          if [[ "${{ runner.os }}" == "Windows" ]]; then
            test -f "target/pack/auroraview-gallery.exe" || (echo "ERROR: Executable not found" && exit 1)
          else
            test -f "target/pack/auroraview-gallery" || (echo "ERROR: Executable not found" && exit 1)
          fi

      - name: Package (Windows)
        if: runner.os == 'Windows'
        shell: pwsh
        run: |
          $artifact = "target/pack/${{ matrix.artifact }}"
          Compress-Archive -Path $artifact -DestinationPath ${{ matrix.archive }}

      - name: Package (Unix)
        if: runner.os != 'Windows'
        run: |
          cd target/pack
          tar -czvf ${{ github.workspace }}/${{ matrix.archive }} ${{ matrix.artifact }}

      - name: Upload artifact
        uses: actions/upload-artifact@v6
        with:
          name: gallery-${{ matrix.target }}
          path: ${{ matrix.archive }}
          if-no-files-found: error

  # Combine all artifacts into one
  # Uses if: always() to run even if some builds fail, ensuring partial releases
  combine-artifacts:
    name: Combine Gallery Artifacts
    runs-on: ubuntu-latest
    needs: build
    if: always() && !cancelled()
    steps:
      - name: Download all artifacts
        uses: actions/download-artifact@v7
        with:
          pattern: gallery-*
          path: artifacts
          merge-multiple: true
        continue-on-error: true

      - name: List artifacts
        run: |
          echo "Available gallery artifacts:"
          if [ -d artifacts ]; then
            ls -la artifacts/ || echo "No artifacts found"
          else
            echo "artifacts directory does not exist"
          fi

      - name: Check if any artifacts exist
        id: check
        run: |
          if [ -d artifacts ] && [ "$(ls -A artifacts 2>/dev/null)" ]; then
            echo "has_artifacts=true" >> $GITHUB_OUTPUT
            echo "Found gallery artifacts to upload"
          else
            echo "has_artifacts=false" >> $GITHUB_OUTPUT
            echo "No gallery artifacts found"
          fi

      - name: Upload combined artifact
        if: steps.check.outputs.has_artifacts == 'true'
        uses: actions/upload-artifact@v6
        with:
          name: gallery-all-platforms
          path: artifacts/*
          if-no-files-found: warn
