name: Zip and Release

on:
  push:
    branches:
      - main
      - master
  workflow_dispatch:

permissions:
  contents: write

jobs:
  zip-and-release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Create zip (flat root, exclude .git)
        run: |
          zip -9 -r repo.zip . -x ".git/*" "repo.zip"

      - name: Generate release metadata and body
        id: meta
        shell: bash
        run: |
          set -euo pipefail
          TS=$(date -u +'%Y%m%d-%H%M%S')
          RAND=$(openssl rand -hex 4)
          NAME="Release-${TS}-${RAND}"
          TAG="tag-${TS}-${RAND}"
          echo "name=$NAME" >> "$GITHUB_OUTPUT"
          echo "tag=$TAG" >> "$GITHUB_OUTPUT"
          {
            echo "Automated release for $GITHUB_REF at $TS (commit $GITHUB_SHA)."
            if jq -e '.commits | length > 0' "$GITHUB_EVENT_PATH" >/dev/null 2>&1; then
              echo
              echo "Changes:"
              jq -r '.commits[] | "- " + (.message | gsub("\r"; "")) + " (" + ((.author.username // .author.name) // "unknown") + ")"' "$GITHUB_EVENT_PATH"
            else
              echo
              echo "Changes:"
              git log -1 --pretty=format:'- %s (%an)'
            fi
          } > RELEASE_BODY.md

      - name: Create GitHub release and upload asset
        uses: softprops/action-gh-release@v2
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          tag_name: ${{ steps.meta.outputs.tag }}
          name: ${{ steps.meta.outputs.name }}
          body_path: RELEASE_BODY.md
          files: repo.zip
          draft: false
          prerelease: false
