name: Build and Push Docker Image

on:
  push:
    branches:
      - main
    tags:
      - 'v*.*.*'

jobs:
  build-and-push:
    name: Build image & push
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    steps:
      # Step 1: Check out the repository
      - name: Checkout code
        uses: actions/checkout@v3

      # Step 2: Extract version from __version__.py
      - name: Extract version
        run: |
          VERSION=$(python -c "exec(open('__version__.py').read()); print(__version__)")
          echo "Version is $VERSION"
          echo "VERSION=$VERSION" >> $GITHUB_ENV

      # Step 3: Log in to GitHub Container Registry
      - name: Log in to GitHub Container Registry
        uses: docker/login-action@v2
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      # Step 4: Build the Docker image
      - name: Build Docker image
        run: |
          docker build -t ghcr.io/${{ github.repository }}:${{ env.VERSION }} .

      # Step 5: Push the Docker image to GHCR
      - name: Push Docker image
        run: |
          docker push ghcr.io/${{ github.repository }}:${{ env.VERSION }}
