name: Auto Tag on Version Change

on:
  push:
    branches:
      - main
    paths:
      - 'pubspec.yaml'

jobs:
  check-version:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6
        with:
          fetch-depth: 2  # Need previous commit to compare

      - name: Get current version
        id: current
        run: |
          VERSION=$(grep '^version:' pubspec.yaml | sed 's/version: //' | cut -d'+' -f1)
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "Current version: $VERSION"

      - name: Get previous version
        id: previous
        run: |
          git checkout HEAD~1 -- pubspec.yaml 2>/dev/null || echo "version: 0.0.0" > pubspec.yaml.old
          if [ -f pubspec.yaml.old ]; then
            VERSION=$(grep '^version:' pubspec.yaml.old | sed 's/version: //' | cut -d'+' -f1)
          else
            VERSION=$(grep '^version:' pubspec.yaml | sed 's/version: //' | cut -d'+' -f1)
          fi
          git checkout HEAD -- pubspec.yaml
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "Previous version: $VERSION"

      - name: Check if version changed
        id: check
        run: |
          CURRENT="${{ steps.current.outputs.version }}"
          PREVIOUS="${{ steps.previous.outputs.version }}"
          
          if [ "$CURRENT" != "$PREVIOUS" ]; then
            echo "Version changed from $PREVIOUS to $CURRENT"
            echo "changed=true" >> $GITHUB_OUTPUT
          else
            echo "Version unchanged: $CURRENT"
            echo "changed=false" >> $GITHUB_OUTPUT
          fi

      - name: Check if tag exists
        id: tag_exists
        if: steps.check.outputs.changed == 'true'
        run: |
          TAG="v${{ steps.current.outputs.version }}"
          if git ls-remote --tags origin | grep -q "refs/tags/$TAG"; then
            echo "Tag $TAG already exists"
            echo "exists=true" >> $GITHUB_OUTPUT
          else
            echo "Tag $TAG does not exist"
            echo "exists=false" >> $GITHUB_OUTPUT
          fi

      - name: Create and push tag
        if: steps.check.outputs.changed == 'true' && steps.tag_exists.outputs.exists == 'false'
        run: |
          TAG="v${{ steps.current.outputs.version }}"
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git tag -a "$TAG" -m "Release $TAG"
          git push origin "$TAG"
          echo "Created and pushed tag: $TAG"
