name: Publish to PyPI (label-gated on main merge)

on:
  push:
    branches: ["main"]

concurrency:
  group: pypi-publish-main
  cancel-in-progress: false

permissions:
  contents: write
  pull-requests: read
  id-token: write

jobs:
  publish:
    runs-on: ubuntu-latest

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

      - name: Detect bump from merged PR labels (patch/minor/major)
        id: bump
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          set -euo pipefail

          PR_JSON="$(curl -sS \
            -H "Authorization: Bearer $GH_TOKEN" \
            -H "Accept: application/vnd.github+json" \
            -H "X-GitHub-Api-Version: 2022-11-28" \
            "https://api.github.com/repos/${GITHUB_REPOSITORY}/commits/${GITHUB_SHA}/pulls")"

          export PR_JSON

          python - <<'PY'
          import json, os, sys

          prs = json.loads(os.environ.get("PR_JSON", "[]"))
          labels = []
          if prs:
            labels = [l["name"].lower() for l in prs[0].get("labels", [])]

          bump = ""
          if "major" in labels:
            bump = "major"
          elif "minor" in labels:
            bump = "minor"
          elif "patch" in labels:
            bump = "patch"

          with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as f:
            f.write(f"bump={bump}\n")

          print("labels =", labels)
          print("bump   =", bump)

          # PR이 연결되지 않거나 라벨이 없으면 bump는 빈 문자열로 유지
          PY

      - name: Skip if no release label
        if: ${{ steps.bump.outputs.bump == '' }}
        run: |
          echo "No release label (patch/minor/major) found on the merged PR. Skipping publish."

      - name: Create and push next version tag
        if: ${{ steps.bump.outputs.bump != '' }}
        id: tag
        run: |
          set -euo pipefail
          git fetch --tags --force

          last_tag="$(git tag --list 'v*' --sort=-v:refname | head -n 1 || true)"
          if [ -z "$last_tag" ]; then
            last_ver="0.0.0"
          else
            last_ver="${last_tag#v}"
          fi

          bump="${{ steps.bump.outputs.bump }}"

          new_ver="$(python - <<PY
          import re
          last="${last_ver}"
          bump="${bump}"
          m=re.match(r"^(\d+)\.(\d+)\.(\d+)$", last)
          if not m:
            raise SystemExit(f"invalid last version: {last}")
          maj, min_, pat = map(int, m.groups())
          if bump == "major":
            maj += 1; min_ = 0; pat = 0
          elif bump == "minor":
            min_ += 1; pat = 0
          else:
            pat += 1
          print(f"{maj}.{min_}.{pat}")
          PY
          )"

          new_tag="v${new_ver}"

          if git rev-parse "$new_tag" >/dev/null 2>&1; then
            echo "ERROR: Tag already exists: $new_tag"
            exit 1
          fi

          git config user.name "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"

          git tag -a "$new_tag" -m "Release $new_tag"
          git push origin "$new_tag"

          echo "new_tag=$new_tag" >> "$GITHUB_OUTPUT"
          echo "new_ver=$new_ver" >> "$GITHUB_OUTPUT"

      - name: Checkout release tag (for setuptools-scm)
        if: ${{ steps.bump.outputs.bump != '' }}
        run: |
          git checkout "${{ steps.tag.outputs.new_tag }}"

      - name: Set up Python
        if: ${{ steps.bump.outputs.bump != '' }}
        uses: actions/setup-python@v5
        with:
          python-version: "3.11"

      - name: Build distributions
        if: ${{ steps.bump.outputs.bump != '' }}
        run: |
          python -m pip install --upgrade pip build
          python -m build

      - name: Check distributions
        if: ${{ steps.bump.outputs.bump != '' }}
        run: |
          python -m pip install --upgrade twine
          python -m twine check dist/*

      - name: Publish to PyPI (Trusted Publishing via OIDC)
        if: ${{ steps.bump.outputs.bump != '' }}
        uses: pypa/gh-action-pypi-publish@release/v1
