name: Build WASM

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
  workflow_dispatch:
    inputs:
      release:
        description: 'Release tag (e.g., v1.0.0). Leave empty for dev build.'
        required: false
        default: ''

env:
  CARGO_TERM_COLOR: always
  RUST_VERSION: nightly
  EMSDK_VERSION: latest

jobs:
  build-wasm:
    runs-on: ubuntu-latest

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

      - name: Install Rust with wasm32-unknown-emscripten target
        uses: dtolnay/rust-toolchain@stable
        with:
          toolchain: ${{ env.RUST_VERSION }}
          target: wasm32-unknown-emscripten

      - name: Setup Emscripten
        uses: mymindstorm/setup-emsdk@v14
        with:
          version: ${{ env.EMSDK_VERSION }}
          no-cache: true

      - name: Install CMake
        run: |
          sudo apt-get update && sudo apt-get install -y cmake

      - name: Clone Unicorn Engine
        id: clone-unicorn
        run: |
          git clone --depth 1 --branch tci-emscripten https://github.com/lbr77/unicorn.git ../unicorn
          echo "unicorn_hash=$(git -C ../unicorn rev-parse HEAD)" >> $GITHUB_OUTPUT

      - name: Cache Unicorn build
        id: cache-unicorn
        uses: actions/cache@v4
        with:
          path: ../unicorn/build
          key: unicorn-build-${{ steps.clone-unicorn.outputs.unicorn_hash }}-${{ runner.os }}

      - name: Build Unicorn
        if: steps.cache-unicorn.outputs.cache-hit != 'true'
        run: |
          bash script/rebuild-unicorn.sh
        env:
          UNICORN_DIR: ${{ github.workspace }}/../unicorn
          UNICORN_BUILD_DIR: ${{ github.workspace }}/../unicorn/build
          JOBS: 4
          EMSDK: ${{ runner.tool_cache }}/emsdk

      - name: Build WASM glue
        run: |
          bash script/build-glue.sh --release
        env:
          UNICORN_BUILD_DIR: ${{ github.workspace }}/../unicorn/build
          EMSDK: ${{ runner.tool_cache }}/emsdk

      - name: Upload WASM artifacts
        uses: actions/upload-artifact@v4
        with:
          name: anisette-wasm
          path: |
            dist/anisette_rs.js
            dist/anisette_rs.wasm
            dist/anisette_rs.node.js
            dist/anisette_rs.node.wasm
          retention-days: 7

      - name: Upload to Release
        if: github.event_name == 'workflow_dispatch' && inputs.release != ''
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ inputs.release }}
          files: |
            dist/anisette_rs.js
            dist/anisette_rs.wasm
            dist/anisette_rs.node.js
            dist/anisette_rs.node.wasm
          generate_release_notes: true
