name: Release

on:
  workflow_call:
    inputs:
      enabled:
        type: boolean
        required: true

jobs:
  release:
    if: inputs.enabled
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v6
        with:
          ref: main
          fetch-depth: 0

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

      - name: Create release
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          # Get version via cargo metadata (official, reliable)
          VERSION=$(cargo metadata --format-version=1 --no-deps | jq -r '.packages[0].version')
          TAG="v$VERSION"
          echo "Version: $TAG"

          # Check if release already exists
          if gh release view "$TAG" &>/dev/null; then
            echo "Release $TAG already exists, skipping"
            exit 0
          fi

          # Create tag if it doesn't exist
          if ! git rev-parse "$TAG" &>/dev/null; then
            git tag "$TAG"
            git push origin "$TAG"
            echo "Created tag $TAG"
          fi

          # Extract release notes from CHANGELOG.md for this version
          # Format: ## [X.Y.Z] - YYYY-MM-DD
          NOTES=$(awk -v ver="$VERSION" '
            $0 ~ "^## \\[" ver "\\]" { found=1; next }
            found && /^## \[/ { exit }
            found && /^---$/ { exit }
            found { print }
          ' CHANGELOG.md)

          if [ -z "$NOTES" ]; then
            NOTES="Release $TAG"
          fi

          echo "Release notes:"
          echo "$NOTES"

          # Create release with tag
          echo "$NOTES" | gh release create "$TAG" --title "$TAG" --notes-file - --latest
