name: Build & Deploy

on:
  push:
    branches: [main]
    tags: ["v*"]

env:
  REGISTRY: gitea.nautilus.marcusgroup.org
  IMAGE: ezer-mishpati/legal-ai

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Login to Gitea Registry
        run: |
          echo "${{ secrets.REGISTRY_PASSWORD }}" | \
            docker login ${{ env.REGISTRY }} \
              -u "${{ secrets.REGISTRY_USER }}" --password-stdin

      - name: Build and tag image
        run: |
          BASE="${{ env.REGISTRY }}/${{ env.IMAGE }}"
          TAGS="-t ${BASE}:latest -t ${BASE}:build-${{ github.run_number }}"

          # If this is a version tag (v*), add the semver tag
          REF="${{ github.ref }}"
          if [[ "$REF" == refs/tags/v* ]]; then
            VERSION="${REF#refs/tags/}"
            TAGS="$TAGS -t ${BASE}:${VERSION}"
            echo "📦 Release: ${VERSION}"
          fi

          echo "🏗️  Building with tags: build-${{ github.run_number }}, latest"
          docker build $TAGS .

      - name: Push image
        run: |
          BASE="${{ env.REGISTRY }}/${{ env.IMAGE }}"
          docker push "${BASE}:latest"
          docker push "${BASE}:build-${{ github.run_number }}"

          REF="${{ github.ref }}"
          if [[ "$REF" == refs/tags/v* ]]; then
            VERSION="${REF#refs/tags/}"
            docker push "${BASE}:${VERSION}"
            echo "✅ Pushed ${VERSION}"
          fi

      - name: Trigger Coolify redeploy
        run: |
          curl -sf \
            "http://coolify:8080/api/v1/deploy?uuid=gyjo0mtw2c42ej3xxvbz8zio&force=true" \
            -H "Authorization: Bearer ${{ secrets.COOLIFY_TOKEN }}"

      - name: Prune old build images and cache
        if: always()
        run: |
          BASE="${{ env.REGISTRY }}/${{ env.IMAGE }}"
          KEEP=5
          # Keep the newest $KEEP build-NNN tags; remove the rest.
          # The build daemon is the shared host daemon, so these images
          # otherwise accumulate in /var/lib/docker (~1.3GB each).
          docker images "${BASE}" --format '{{.Tag}}' \
            | grep -E '^build-[0-9]+$' \
            | sort -t- -k2 -nr \
            | tail -n +$((KEEP + 1)) \
            | while read -r tag; do
                echo "🗑️  Removing ${BASE}:${tag}"
                docker rmi "${BASE}:${tag}" || true
              done
          # Dangling images + build cache older than 72h (keeps recent layers warm)
          docker image prune -f || true
          docker builder prune -f --filter 'until=72h' || true
