name: Publish to PyPI

on:
  release:
    types: [published]

permissions:
  contents: read

jobs:
  test:
    runs-on: ubuntu-latest
    timeout-minutes: 20
    steps:
      - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
      - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
        with:
          python-version: "3.12"
          cache: 'pip'
          cache-dependency-path: pyproject.toml
      - name: Install dependencies
        run: pip install -e ".[all,dev]"
      - name: Run tests (gate — deterministic, no network)
        # Issue #426: a transient HuggingFace download flake must not block a
        # release of correct code. Network-marked tests run separately in CI.
        env:
          HF_HUB_OFFLINE: "1"
          TRANSFORMERS_OFFLINE: "1"
        run: pytest tests/ -v -m "not network"
      - name: Lint
        run: ruff check truememory/ tests/

  build-check:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
      - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
        with:
          python-version: "3.12"
          cache: 'pip'
          cache-dependency-path: pyproject.toml
      - name: Install build tooling
        run: pip install build twine
      - name: Build sdist + wheel
        run: python -m build
      - name: Verify package metadata
        run: twine check --strict dist/*

  version-check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
      - name: Verify tag matches pyproject.toml version
        run: |
          TAG="${GITHUB_REF_NAME#v}"
          VERSION=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")
          if [ "$TAG" != "$VERSION" ]; then
            echo "ERROR: Git tag ($TAG) does not match pyproject.toml version ($VERSION)"
            exit 1
          fi
          echo "OK: tag=$TAG matches pyproject.toml version=$VERSION"

  publish:
    needs: [test, build-check, version-check]
    runs-on: ubuntu-latest
    environment: pypi
    permissions:
      id-token: write
    steps:
      - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
        with:
          persist-credentials: false

      - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
        with:
          python-version: "3.12"

      - name: Install build tools
        run: pip install build

      - name: Build package
        run: python -m build

      - name: Publish to PyPI
        uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b # v1.14.0
