name: Auto Release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: write
  id-token: write

jobs:
  test:
    name: "Test before release"
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: actions/setup-python@v5
        with:
          python-version: "3.13"
      - name: Install & test
        run: |
          pip install -e .
          pip install pytest pytest-cov
          pytest tests/ --cov=strands_inspect --cov-fail-under=80 -v

  publish:
    name: "Publish to PyPI"
    needs: test
    runs-on: ubuntu-latest
    environment:
      name: pypi
      url: https://pypi.org/p/strands-inspect
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - uses: actions/setup-python@v5
        with:
          python-version: "3.13"

      - name: Install build tools
        run: pip install build twine

      - name: Verify version from tag
        run: |
          pip install -e .
          TAG=${GITHUB_REF#refs/tags/v}
          PKG_VERSION=$(python -c "import strands_inspect; print(strands_inspect.__version__)")
          echo "Git tag: $TAG"
          echo "Package version: $PKG_VERSION"

      - name: Build
        run: python -m build

      - name: Check dist
        run: twine check dist/*

      - name: Publish to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1

  github-release:
    name: "GitHub Release"
    needs: publish
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Generate changelog
        id: changelog
        run: |
          TAG=${GITHUB_REF#refs/tags/}
          PREV_TAG=$(git tag --sort=-creatordate | grep -v "^$TAG$" | head -1)
          if [ -z "$PREV_TAG" ]; then
            LOG=$(git log --pretty=format:"- %s (%h)" HEAD)
          else
            LOG=$(git log --pretty=format:"- %s (%h)" "$PREV_TAG".."$TAG")
          fi
          echo "CHANGELOG<<EOF" >> $GITHUB_ENV
          echo "$LOG" >> $GITHUB_ENV
          echo "EOF" >> $GITHUB_ENV

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          body: |
            ## What's Changed
            ${{ env.CHANGELOG }}

            ## Install
            ```
            pip install strands-inspect==${{ github.ref_name }}
            ```
          generate_release_notes: true
