name: Publish to crates.io

on:
  push:
    tags:
      - 'v*'

jobs:
  publish:
    name: Publish
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: wasm32-unknown-unknown

      - name: Cache cargo registry (registry only, not target)
        uses: actions/cache@v5
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
          key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: ${{ runner.os }}-cargo-

      - name: Install trunk
        run: cargo install --locked trunk

      - name: Build UI
        run: cargo check
        # Runs build.rs fresh (no target cache) → trunk inlines Yew UI → writes prebuilt.html
        # at the package root (not ui/): ui/ is a separate workspace member and
        # cargo publish strips it from the moadim tarball.

      - name: Verify prebuilt UI was generated
        run: test -s prebuilt.html || (echo "prebuilt.html missing or empty" && exit 1)

      - name: Verify prebuilt UI ships in the published tarball
        run: cargo package --list --allow-dirty | grep -qx prebuilt.html || (echo "prebuilt.html not in package tarball" && exit 1)

      - name: Commit prebuilt UI so cargo publish includes it
        run: |
          git config user.email "actions@github.com"
          git config user.name "GitHub Actions"
          git add prebuilt.html
          git commit -m "ci: bundle prebuilt UI"

      - name: Verify tag matches Cargo.toml version
        run: |
          CARGO_VERSION=$(grep '^version' Cargo.toml | head -1 | sed 's/version = "\(.*\)"/\1/')
          TAG_VERSION=${GITHUB_REF_NAME#v}
          if [ "$CARGO_VERSION" != "$TAG_VERSION" ]; then
            echo "Version mismatch: Cargo.toml=$CARGO_VERSION, tag=$TAG_VERSION"
            exit 1
          fi

      - name: Publish
        run: cargo publish --token ${{ secrets.CARGO_REGISTRY_TOKEN }} --allow-dirty
