name: CI

on:
  push:
    branches: [main]
    tags: ['v*']
  pull_request:
    branches: [main]

jobs:
  test:
    name: Test (Python ${{ matrix.python-version }})
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        python-version: ["3.11", "3.12"]

    steps:
      - uses: actions/checkout@v5

      - name: Set up Python ${{ matrix.python-version }}
        uses: actions/setup-python@v5
        with:
          python-version: ${{ matrix.python-version }}
          cache: pip

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -e ".[dev]"

      - name: Lint with ruff
        run: ruff check clawstu tests

      - name: Type-check with mypy
        run: mypy clawstu

      - name: Run tests with coverage
        run: pytest --cov=clawstu --cov-report=term --cov-report=xml

      - name: Upload coverage artifact
        if: matrix.python-version == '3.11'
        uses: actions/upload-artifact@v4
        with:
          name: coverage-report
          path: coverage.xml

  publish:
    if: startsWith(github.ref, 'refs/tags/v')
    needs: [test]
    runs-on: ubuntu-latest
    environment: pypi
    permissions:
      id-token: write
      contents: read
    steps:
      - uses: actions/checkout@v5
      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'
      - name: Install build tools
        run: python -m pip install --upgrade pip build twine pkginfo
      - name: Build sdist + wheel
        run: python -m build
      - name: Verify distribution name
        run: |
          ls dist/
          python <<'PY'
          import glob, pkginfo
          sdists = glob.glob('dist/clawstu-*.tar.gz')
          assert len(sdists) == 1, sdists
          p = pkginfo.SDist(sdists[0])
          assert p.name == 'clawstu', p.name
          print(f"Verified: {p.name} {p.version}")
          PY
      - name: Publish to PyPI
        # No `|| echo` fallback: real twine failures must fail the job.
        # --skip-existing handles the benign "version already uploaded" case.
        run: twine upload --skip-existing dist/*
        env:
          TWINE_USERNAME: __token__
          TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }}
          TWINE_NON_INTERACTIVE: "1"
