#!/usr/bin/env python3
import sys, re
from pathlib import Path

ROOT = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(".")
BASE = ROOT / "frontend" / "public"
if not BASE.exists():
    print(f"❌ Dossier introuvable: {BASE}")
    sys.exit(1)

script_tag = '<script type="module" src="/assets/header.js?v=1"></script>'

html_files = list(BASE.rglob("*.html"))
changed = 0

for p in html_files:
    s = p.read_text(encoding="utf-8", errors="ignore")
    if "assets/header.js" in s:
        continue  # déjà injecté

    # insertion juste avant </body> (insensible à la casse/espaces)
    new_s, n = re.subn(r"</body\s*>", f"  {script_tag}\n</body>", s, flags=re.IGNORECASE)
    if n == 0:
        # si pas de </body>, on append à la fin
        new_s = s + "\n" + script_tag + "\n"
    p.write_text(new_s, encoding="utf-8")
    print(f"➕ header.js -> {p}")
    changed += 1

print(f"✅ Injection terminée ({changed} modification(s)).")