# =============================================================================
# MCP GHCR Build — Build Docker image and push to GitHub Container Registry
# =============================================================================
#
# Triggered on push to main or dev, and on manual dispatch.
# - main: pushes :latest and :sha-XXXXXXX tags
# - dev:  pushes :dev and :sha-XXXXXXX tags
#
# Watchtower on the Hetzner prod server polls GHCR every 6 hours and
# automatically restarts containers when a new :latest image is detected.
# No manual deploy step needed.
#
# PREREQUISITES:
# 1. Repository must have a Dockerfile at the root (or specify path)
# 2. GITHUB_TOKEN has automatic write:packages permission (no secrets needed)
#
# =============================================================================

name: Build and Push to GHCR

on:
  push:
    branches: [main, dev]
  workflow_dispatch:

concurrency:
  group: build-${{ github.ref }}
  cancel-in-progress: true

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: israel-law-mcp

permissions:
  contents: read
  packages: write

jobs:
  build-and-push:
    name: Build and Push
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

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

      - name: Extract metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/ansvar-systems/${{ env.IMAGE_NAME }}
          tags: |
            type=raw,value=latest,enable=${{ github.ref == format('refs/heads/{0}', 'main') }}
            type=raw,value=dev,enable=${{ github.ref == 'refs/heads/dev' }}
            type=sha,prefix=sha-,format=short

      - name: Build and push
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          platforms: linux/amd64
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Summary
        if: always()
        run: |
          echo "## GHCR Build" >> "$GITHUB_STEP_SUMMARY"
          echo "" >> "$GITHUB_STEP_SUMMARY"
          echo "| Field | Value |" >> "$GITHUB_STEP_SUMMARY"
          echo "|-------|-------|" >> "$GITHUB_STEP_SUMMARY"
          echo "| Image | \`${{ env.REGISTRY }}/ansvar-systems/${{ env.IMAGE_NAME }}\` |" >> "$GITHUB_STEP_SUMMARY"
          echo "| Tags | $(echo '${{ steps.meta.outputs.tags }}' | tr '\n' ', ') |" >> "$GITHUB_STEP_SUMMARY"
          echo "| Branch | \`${{ github.ref_name }}\` |" >> "$GITHUB_STEP_SUMMARY"
          echo "| Commit | \`${{ github.sha }}\` |" >> "$GITHUB_STEP_SUMMARY"