#!/bin/bash
# ═══════════════════════════════════════════════════════════════
# deploy-prod.sh — Déploiement automatique branche "main"
# Cron : 0 * * * * /home/fase0445/deploy-prod.sh >> /home/fase0445/logs/prod.log 2>&1
# ═══════════════════════════════════════════════════════════════

FRONT_DIR="/home/fase0445/public_html/uluana/frontend"
BACK_DIR="/home/fase0445/public_html/uluana/backend"
BRANCH="main"
LOG_PREFIX="[$(date '+%Y-%m-%d %H:%M:%S')] [PROD]"

git -C "$FRONT_DIR" fetch origin "$BRANCH" --quiet
git -C "$BACK_DIR"  fetch origin "$BRANCH" --quiet

FRONT_LOCAL=$(git -C "$FRONT_DIR" rev-parse HEAD)
FRONT_REMOTE=$(git -C "$FRONT_DIR" rev-parse "origin/$BRANCH")
BACK_LOCAL=$(git -C "$BACK_DIR" rev-parse HEAD)
BACK_REMOTE=$(git -C "$BACK_DIR" rev-parse "origin/$BRANCH")

if [ "$FRONT_LOCAL" = "$FRONT_REMOTE" ] && [ "$BACK_LOCAL" = "$BACK_REMOTE" ]; then
    exit 0
fi

echo "$LOG_PREFIX Nouvelle version détectée, déploiement..."

if [ "$FRONT_LOCAL" != "$FRONT_REMOTE" ]; then
    # reset --hard plutôt que pull : un déploiement doit toujours faire
    # correspondre EXACTEMENT le serveur à la branche distante, y compris si
    # son historique a été réécrit (ex: un force-push après une réécriture de
    # main) — un simple "git pull" échoue alors avec "divergent branches" et
    # bloque tout déploiement suivant, indéfiniment, tant que ce n'est pas
    # corrigé à la main.
    git -C "$FRONT_DIR" reset --hard "origin/$BRANCH" --quiet
    [ $? -ne 0 ] && echo "$LOG_PREFIX ERREUR git reset frontend" && exit 1
    echo "$LOG_PREFIX Frontend mis à jour"
fi

if [ "$BACK_LOCAL" != "$BACK_REMOTE" ]; then
    git -C "$BACK_DIR" reset --hard "origin/$BRANCH" --quiet
    [ $? -ne 0 ] && echo "$LOG_PREFIX ERREUR git reset backend" && exit 1
    echo "$LOG_PREFIX Backend mis à jour"

    # Dépendances Composer (dompdf pour la fiche PDF terrain) — non bloquant :
    # si composer est absent sur l'hébergement, le reste du déploiement continue,
    # seule la génération de fiche PDF sera indisponible.
    if command -v composer >/dev/null 2>&1; then
        HOME=/home/fase0445 COMPOSER_HOME=/home/fase0445/.composer composer install --no-dev --optimize-autoloader --working-dir="$BACK_DIR" --quiet
        [ $? -ne 0 ] && echo "$LOG_PREFIX ATTENTION composer install a échoué (fiche PDF indisponible)"
    else
        echo "$LOG_PREFIX ATTENTION composer introuvable (fiche PDF indisponible)"
    fi
fi

php "$BACK_DIR/deploy/migrate.php"
[ $? -ne 0 ] && echo "$LOG_PREFIX ERREUR migrations SQL" && exit 1

# ── Import catalogue (cards/guides/exemples/quiz — pas de données users/actions) ──
php "$BACK_DIR/import-catalogue.php"
[ $? -ne 0 ] && echo "$LOG_PREFIX ERREUR import catalogue" && exit 1

# ── Import enrichissement PDF (comment_faire_par_etape/exemples_concrets validés) ──
php "$BACK_DIR/import-enrichissement.php" --all
[ $? -ne 0 ] && echo "$LOG_PREFIX ERREUR import enrichissement" && exit 1

# ── Import cartes en attente (_cards_pending_import.json) ──
PENDING="$BACK_DIR/data/cards/_cards_pending_import.json"
SEED="$BACK_DIR/data/cards/_cards_pending_import.seed.json"
[ ! -f "$PENDING" ] && echo '{"pending":[]}' > "$PENDING"
[ -f "$SEED" ] && php -r "
  \$seed = json_decode(file_get_contents('$SEED'), true)['pending'] ?? [];
  \$p    = json_decode(file_get_contents('$PENDING'), true);
  \$ids  = array_column(\$p['pending'] ?? [], 'updated_at', 'id');
  foreach (\$seed as \$e) {
    if (!isset(\$ids[\$e['id']]) || \$ids[\$e['id']] < \$e['updated_at'])
      \$p['pending'][] = \$e;
  }
  \$byId = [];
  foreach (\$p['pending'] as \$e) {
    if (!isset(\$byId[\$e['id']]) || \$byId[\$e['id']]['updated_at'] < \$e['updated_at'])
      \$byId[\$e['id']] = \$e;
  }
  \$p['pending'] = array_values(\$byId);
  file_put_contents('$PENDING', json_encode(\$p, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
"
php "$BACK_DIR/api/import_cards.php" || echo "$LOG_PREFIX WARN import_cards non bloquant"

echo "$LOG_PREFIX Déploiement OK"
