#!/usr/bin/env bash
# =============================================================================
#  02-build-and-push.sh
#  À EXÉCUTER SUR TON POSTE DE DEV.
#
#  Build des DEUX images OSEP depuis le Dockerfile multi-target :
#    - kplan-www:TAG       (target: php)
#    - kplan-www-nginx:TAG (target: nginx, avec assets bakés)
#
#  Les deux partagent le même TAG → atomicité garantie.
#  Validation hard du bundle CSS avant push.
# =============================================================================

set -euo pipefail

DOCKERHUB_USER="${DOCKERHUB_USER:-massambafall92}"
PHP_IMAGE="${PHP_IMAGE:-${DOCKERHUB_USER}/kplan-www}"
NGINX_IMAGE="${NGINX_IMAGE:-${DOCKERHUB_USER}/kplan-www-nginx}"
DOCKERFILE="${DOCKERFILE:-docker/stack/Dockerfile}"
PLATFORM="linux/amd64"

if [ -t 1 ]; then
    C_BLUE='\033[1;34m'; C_GREEN='\033[1;32m'; C_YELLOW='\033[1;33m'
    C_RED='\033[1;31m';  C_DIM='\033[2m';      C_RESET='\033[0m'
else
    C_BLUE=''; C_GREEN=''; C_YELLOW=''; C_RED=''; C_DIM=''; C_RESET=''
fi
log()  { printf "${C_BLUE}▸ %s${C_RESET}\n" "$*"; }
ok()   { printf "${C_GREEN}✓ %s${C_RESET}\n" "$*"; }
warn() { printf "${C_YELLOW}⚠ %s${C_RESET}\n" "$*"; }
err()  { printf "${C_RED}✗ %s${C_RESET}\n" "$*" >&2; }

# Pré-flight
[ -f "$DOCKERFILE" ] || { err "Dockerfile introuvable : $DOCKERFILE"; exit 1; }
docker buildx version >/dev/null || { err "docker buildx absent"; exit 1; }

# Sources — vérif osep.scss
LOCAL_OSEP=$(grep -c "osep-" assets/styles/osep.scss 2>/dev/null || echo 0)
LOCAL_IMPORT=$(grep -c '@import "./osep.scss"' assets/styles/app.scss 2>/dev/null || echo 0)
[ "$LOCAL_OSEP" -gt 100 ] || { err "osep.scss n'a que $LOCAL_OSEP classes osep-"; exit 1; }
[ "$LOCAL_IMPORT" -ge 1 ] || { err "app.scss n'importe pas osep.scss"; exit 1; }
ok "Sources OK : $LOCAL_OSEP classes dans osep.scss"

# Login
if ! docker info 2>/dev/null | grep -q "Username:"; then
    docker login -u "$DOCKERHUB_USER"
fi

# Tag
SHA=$(git rev-parse --short=7 HEAD 2>/dev/null || echo nogit)
TAG="$(date +%Y%m%d%H%M)-${SHA}"

PHP_FULL="${PHP_IMAGE}:${TAG}"
NGINX_FULL="${NGINX_IMAGE}:${TAG}"

echo
log "Images qui seront produites :"
echo "    $PHP_FULL"
echo "    $NGINX_FULL"
echo

# Build target php
log "Build target=php (sans cache)..."
docker buildx build \
    --no-cache \
    --target php \
    --platform "$PLATFORM" \
    -f "$DOCKERFILE" \
    -t "$PHP_FULL" \
    -t "${PHP_IMAGE}:latest" \
    --push \
    .
ok "Image PHP poussée : $PHP_FULL"

# Build target nginx (réutilise le cache du stage assets)
log "Build target=nginx..."
docker buildx build \
    --target nginx \
    --platform "$PLATFORM" \
    -f "$DOCKERFILE" \
    -t "$NGINX_FULL" \
    -t "${NGINX_IMAGE}:latest" \
    --push \
    .
ok "Image nginx poussée : $NGINX_FULL"

# Validation
log "Validation des deux images..."
for IMG in "$PHP_FULL" "$NGINX_FULL"; do
    docker pull "$IMG" >/dev/null
    COUNT=$(docker run --rm --entrypoint sh "$IMG" -c '
        APP_CSS=$(find /var/www/public/build -name "app.*.css" 2>/dev/null | head -1)
        [ -z "$APP_CSS" ] && exit 1
        grep -c "osep-" "$APP_CSS"
    ' 2>/dev/null || echo 0)

    if [ "$COUNT" -lt 1000 ]; then
        err "$IMG : seulement $COUNT classes osep-  (attendu > 1000)"
        exit 1
    fi
    ok "$IMG : $COUNT classes osep- ✓"
done

echo
ok "Build & push complets"
echo
cat <<EOF
${C_DIM}── Étape suivante ──────────────────────────────────────────────────${C_RESET}

Sur le serveur :

    ${C_DIM}export KPLAN_IMAGE_TAG=${TAG}${C_RESET}
    ${C_DIM}sudo /opt/kplan/scripts/03-redeploy.sh${C_RESET}

EOF

echo "$TAG" > .last-build-tag
