name: Release

on:
  release:
    types: [published]
  workflow_dispatch:
    inputs:
      dry_run:
        description: "Run cargo publish without uploading"
        required: true
        default: "true"
        type: choice
        options:
          - "true"
          - "false"

jobs:
  publish:
    name: Publish crate
    runs-on: ubuntu-latest
    environment: crates.io
    permissions:
      contents: read
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          components: clippy, rustfmt

      - name: Verify tag matches Cargo version
        if: github.event_name == 'release'
        shell: bash
        run: |
          version="$(cargo pkgid | sed 's/.*#//')"
          tag="${GITHUB_REF_NAME#v}"
          if [[ "$version" != "$tag" ]]; then
            echo "Cargo.toml version ($version) does not match release tag ($GITHUB_REF_NAME)"
            exit 1
          fi

      - name: Check formatting
        run: cargo fmt --check

      - name: Run Clippy
        run: cargo clippy --all-targets -- -D warnings

      - name: Run tests
        run: cargo test

      - name: Run examples
        run: |
          cargo run --example basic
          cargo run --example components
          cargo run --example htmx_fragments

      - name: Build documentation
        env:
          RUSTDOCFLAGS: -D warnings
        run: cargo doc --no-deps

      - name: Package crate
        run: cargo package

      - name: Dry-run publish
        if: github.event_name == 'workflow_dispatch' && inputs.dry_run == 'true'
        run: cargo publish --dry-run

      - name: Publish to crates.io
        if: github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && inputs.dry_run == 'false')
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
        run: cargo publish
