name: Create Release

on:
  push:
    tags:
      - 'v*'

jobs:
  release:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract version from tag
        id: version
        run: |
          VERSION=${GITHUB_REF#refs/tags/}
          echo "tag=$VERSION" >> $GITHUB_OUTPUT
          echo "Building release for $VERSION"

      - name: Check if release already exists
        id: check_release
        run: |
          chmod +x .github/workflows/scripts/check-release-exists.sh
          .github/workflows/scripts/check-release-exists.sh ${{ steps.version.outputs.tag }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Create release package variants
        if: steps.check_release.outputs.exists == 'false'
        run: |
          chmod +x .github/workflows/scripts/create-release-packages.sh
          .github/workflows/scripts/create-release-packages.sh ${{ steps.version.outputs.tag }}

      - name: Generate release notes
        if: steps.check_release.outputs.exists == 'false'
        id: release_notes
        run: |
          chmod +x .github/workflows/scripts/generate-release-notes.sh
          # Get the previous tag for changelog generation
          PREVIOUS_TAG=$(git describe --tags --abbrev=0 ${{ steps.version.outputs.tag }}^ 2>/dev/null || echo "")
          # Default to v0.0.0 if no previous tag is found (e.g., first release)
          if [ -z "$PREVIOUS_TAG" ]; then
            PREVIOUS_TAG="v0.0.0"
          fi
          .github/workflows/scripts/generate-release-notes.sh ${{ steps.version.outputs.tag }} "$PREVIOUS_TAG"

      - name: Create GitHub Release
        if: steps.check_release.outputs.exists == 'false'
        run: |
          chmod +x .github/workflows/scripts/create-github-release.sh
          .github/workflows/scripts/create-github-release.sh ${{ steps.version.outputs.tag }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

