#!/usr/bin/env bash
set -euo pipefail

ROOT="${1:-.}"
BASE="$ROOT/frontend/public"

[ -d "$BASE" ] || { echo "❌ Dossier $BASE introuvable"; exit 1; }

link_css='<link rel="stylesheet" href="/assets/patch-bubbles.css?v=2" />'
script_js='<script type="module" src="/assets/bubbles.js?v=2"></script>'

changed=0
# Boucle sur tous les .html (récursif via find, compatible macOS)
while IFS= read -r -d '' page; do
  # Inject CSS avant </head>
  if ! grep -q 'patch-bubbles.css' "$page"; then
    sed -i '' -e "s#</head>#  ${link_css}\n</head>#g" "$page"
    echo "➕ CSS -> $page"
    changed=$((changed+1))
  fi
  # Inject JS avant </body>
  if ! grep -q 'bubbles.js' "$page"; then
    sed -i '' -e "s#</body>#  ${script_js}\n</body>#g" "$page"
    echo "➕ JS  -> $page"
    changed=$((changed+1))
  fi
done < <(find "$BASE" -type f -name "*.html" -print0)

echo "✅ Injection terminée (${changed} modifications)."