name: Release

on:
  push:
    branches:
      - main
      - master

jobs:
  release:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      id-token: write
      attestations: write

    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'

      - name: Get version from package.json
        id: version
        run: echo "version=$(node -p "require('./package.json').version")" >> $GITHUB_OUTPUT

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

      - name: Install dependencies
        if: steps.check_tag.outputs.exists == 'false'
        run: npm ci

      - name: Validate manifest.json version
        if: steps.check_tag.outputs.exists == 'false'
        run: |
          MANIFEST_VERSION=$(node -p "require('./manifest.json').version || ''")
          PACKAGE_VERSION=$(node -p "require('./package.json').version")
          if [ -z "$MANIFEST_VERSION" ]; then
            echo "::error::manifest.json is missing the 'version' field"
            exit 1
          fi
          if [ "$MANIFEST_VERSION" != "$PACKAGE_VERSION" ]; then
            echo "::error::manifest.json version ($MANIFEST_VERSION) does not match package.json version ($PACKAGE_VERSION)"
            exit 1
          fi

      - name: Build
        if: steps.check_tag.outputs.exists == 'false'
        run: npm run build

      - name: Attest release assets
        if: steps.check_tag.outputs.exists == 'false'
        uses: actions/attest-build-provenance@v2
        with:
          subject-path: |
            main.js
            manifest.json
            styles.css

      - name: Create Release
        if: steps.check_tag.outputs.exists == 'false'
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ steps.version.outputs.version }}
          draft: true
          files: |
            main.js
            manifest.json
            styles.css
          generate_release_notes: true
