name: Release Obsidian plugin

on:
  push:
    tags:
      - "*"

jobs:
  build:
    runs-on: ubuntu-latest

    permissions:
      contents: write
      attestations: write
      id-token: write

    steps:
      - uses: actions/checkout@v4

      - name: Use Node.js
        uses: actions/setup-node@v4
        with:
          node-version: "20.x"

      - name: Build plugin
        run: |
          npm install
          npm run build

      - name: Generate artifact attestations
        uses: actions/attest-build-provenance@v2
        with:
          subject-path: |
            main.js
            styles.css

      - name: Extract release notes from CHANGELOG
        id: changelog
        run: |
          tag="${GITHUB_REF#refs/tags/}"
          # Derive the minor version prefix (e.g. "1.6" from "1.6.1")
          minor=$(echo "$tag" | sed 's/\.[0-9]*$//')

          # Collect all patch versions of this minor series present in CHANGELOG,
          # in the order they appear (newest first).
          # Each version block runs from its "## [X.Y.Z]" heading to the next "## [" heading.
          python3 - "$minor" <<'PYEOF' > release_notes.md
          import sys, re

          minor = sys.argv[1]

          with open("CHANGELOG.md", "r", encoding="utf-8") as f:
              content = f.read()

          # Split into version blocks on "## [x.y.z]" headings
          pattern = re.compile(r'^(## \[\d+\.\d+\.\d+\].*?)(?=^## \[|\Z)', re.MULTILINE | re.DOTALL)
          blocks = pattern.findall(content)

          output = []
          for block in blocks:
              # Check if this block belongs to our minor version
              heading_match = re.match(r'^## \[(\d+\.\d+)\.\d+\]', block)
              if heading_match and heading_match.group(1) == minor:
                  # Strip trailing whitespace and trailing "---" separator
                  cleaned = re.sub(r'\n---\s*$', '', block.strip())
                  output.append(cleaned)

          print("\n\n".join(output))
          PYEOF

      - name: Create release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          tag="${GITHUB_REF#refs/tags/}"

          gh release create "$tag" \
            --title="$tag" \
            --draft \
            --notes-file release_notes.md \
            main.js manifest.json styles.css

