name: Release

on:
  push:
    branches: [main, master]
  workflow_dispatch:

permissions:
  contents: write

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable

      - name: Cache cargo registry and target
        uses: Swatinem/rust-cache@v2

      - name: Read version from Cargo.toml
        id: version
        run: |
          VERSION=$(cargo metadata --no-deps --format-version 1 \
            | python3 -c "import json,sys; pkgs=json.load(sys.stdin)['packages']; p=[x for x in pkgs if x['name']=='mii-http'][0]; print(p['version'])")
          echo "version=$VERSION" >> "$GITHUB_OUTPUT"
          echo "tag=v$VERSION" >> "$GITHUB_OUTPUT"
          echo "Detected version: $VERSION"

      - name: Check if tag already exists
        id: tag_check
        run: |
          if git rev-parse "refs/tags/${{ steps.version.outputs.tag }}" >/dev/null 2>&1; then
            echo "exists=true" >> "$GITHUB_OUTPUT"
            echo "Tag ${{ steps.version.outputs.tag }} already exists; skipping release."
          else
            echo "exists=false" >> "$GITHUB_OUTPUT"
          fi

      - name: Build
        if: steps.tag_check.outputs.exists == 'false'
        run: cargo build --release --locked

      - name: Test
        if: steps.tag_check.outputs.exists == 'false'
        run: cargo test --release --locked

      - name: Publish to crates.io
        if: steps.tag_check.outputs.exists == 'false'
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
        run: cargo publish --locked

      - name: Create and push git tag
        if: steps.tag_check.outputs.exists == 'false'
        env:
          TAG: ${{ steps.version.outputs.tag }}
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git tag -a "$TAG" -m "Release $TAG"
          git push origin "$TAG"

      - name: Create GitHub Release
        if: steps.tag_check.outputs.exists == 'false'
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          TAG: ${{ steps.version.outputs.tag }}
          VERSION: ${{ steps.version.outputs.version }}
        run: |
          PRERELEASE_FLAG=""
          case "$VERSION" in
            *-*) PRERELEASE_FLAG="--prerelease" ;;
          esac
          gh release create "$TAG" --generate-notes $PRERELEASE_FLAG
