name: build-stt-server

# Construit l'image du STT-server, la tague par SHA de commit, et (sur main) met à jour
# le manifest k8s avec ce tag → ArgoCD déploie une image immuable et déterministe.
on:
  push:
    branches: ["main", "claude/**"]
    paths:
      - "stt/server/**"
      - "!stt/server/**/*.md"   # les changements doc-only ne rebuildent pas l'image
      - ".github/workflows/build-stt-server.yml"
  workflow_dispatch:

env:
  IMAGE: ghcr.io/alkatrazz24/funk-stt-server

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: write   # pour committer le bump du manifest sur main
      packages: write
    steps:
      - uses: actions/checkout@v4

      - name: Calcule le tag (SHA court) + la liste des tags
        id: vars
        run: |
          TAG="sha-$(git rev-parse --short=7 HEAD)"
          echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
          if [ "${{ github.ref }}" = "refs/heads/main" ]; then
            echo "tags=${IMAGE}:${TAG},${IMAGE}:latest" >> "$GITHUB_OUTPUT"
          else
            echo "tags=${IMAGE}:${TAG}" >> "$GITHUB_OUTPUT"
          fi

      - name: Log in to GHCR
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build & push
        uses: docker/build-push-action@v6
        with:
          context: stt/server
          push: true
          tags: ${{ steps.vars.outputs.tags }}

      - name: Met à jour le manifest avec le tag SHA (main uniquement)
        if: github.ref == 'refs/heads/main'
        run: |
          sed -i "s|image: ${IMAGE}:.*|image: ${IMAGE}:${{ steps.vars.outputs.tag }}|" \
            k8s/apps/stt/deployment.yaml
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add k8s/apps/stt/deployment.yaml
          if ! git diff --staged --quiet; then
            git commit -m "ci(stt): image → ${{ steps.vars.outputs.tag }} [skip ci]"
            git pull --rebase origin main
            git push
          fi
