name: auto-merge-release

on:
  schedule:
    - cron: "0 10 * * *"
  workflow_dispatch:

permissions: {}

concurrency:
  group: auto-merge-release
  cancel-in-progress: false

jobs:
  merge:
    if: github.repository == 'jdx/hk'
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # zizmor: ignore[artipacked] v6
        with:
          fetch-depth: 0
          fetch-tags: true
          persist-credentials: false
      - name: Merge release into main
        run: |
          set -euo pipefail

          if [ "${GITHUB_EVENT_NAME:-}" != "workflow_dispatch" ]; then
            latest_tag=$(git describe --tags --match 'v[0-9]*' --abbrev=0 || true)
            if [ -n "$latest_tag" ]; then
              range="${latest_tag}..HEAD"
              tag_time=$(git for-each-ref --format='%(creatordate:unix)' "refs/tags/$latest_tag")
              now=$(date +%s)
              min_age=$((7 * 24 * 60 * 60))
              age=$((now - tag_time))
              if [ "$age" -lt "$min_age" ]; then
                echo "Latest release ${latest_tag} is less than 7 days old; not auto-merging release PRs"
                exit 0
              fi
            else
              echo "No v[0-9]* release tag found; allowing bootstrap release"
              range=""
            fi
            if [ -n "$range" ]; then
              commit_subjects=$(git log --format=%s "$range")
              if ! grep -Eq '^(fix|feat)(\([^)]+\))?!?: ' <<<"$commit_subjects"; then
                echo "No pending fix/feat commits since the latest release; not auto-merging release PRs"
                exit 0
              fi
            fi
          else
            echo "Manual dispatch; skipping release cadence guards"
          fi

          PR_NUMBER=$(gh pr list -R jdx/hk --base main --head release --state open --limit 100 --json number,headRefName,headRepositoryOwner \
            --jq '[.[] | select(.headRefName == "release") | select(.headRepositoryOwner.login == "jdx")][0].number // empty')
          if [ -z "$PR_NUMBER" ]; then
            echo "No open PR from release to main"
            exit 0
          fi

          BODY=$(gh pr view "$PR_NUMBER" -R jdx/hk --json body --jq '.body // ""')
          TRIMMED_BODY=$(echo "$BODY" | tr -d '[:space:]')
          if [ -z "$TRIMMED_BODY" ]; then
            echo "Skipping merge: PR #$PR_NUMBER has an empty body; will retry on the next scheduled run"
            exit 0
          fi

          echo "PR #$PR_NUMBER is ready for the daily release window"
          gh pr merge "$PR_NUMBER" -R jdx/hk --squash --auto
        env:
          GH_TOKEN: ${{ secrets.HK_GH_TOKEN }}
