#!/usr/bin/env bash
# Convention du 11/08 (Enguerran) : les documents destinés aux HUMAINS existent en Word,
# les .md restent la source de travail. Ce script régénère les .docx depuis les .md —
# jamais l'inverse : le .md fait foi, le .docx est une vue.
#
# Usage : scripts/doc_word.sh docs/roadmap/14_REGLES_GIT.md   (ou sans argument : les docs clés)
set -euo pipefail

convertir() {
  local md="$1"
  local docx="${md%.md}.docx"
  local html
  html=$(mktemp /tmp/docXXXX.html)
  # markdown → html via python (pas de dépendance externe), puis html → docx via textutil (macOS)
  python3 - "$md" > "$html" <<'PY'
import sys, html as h, re
src = open(sys.argv[1], encoding="utf-8").read()
lignes = src.split("\n")
out = ["<html><head><meta charset='utf-8'><style>body{font-family:Calibri,Arial,sans-serif;font-size:12pt;line-height:1.5}h1{font-size:20pt}h2{font-size:16pt}h3{font-size:13pt}table{border-collapse:collapse}td,th{border:1px solid #999;padding:6px 10px}code{font-family:Consolas,monospace;background:#f0f0f0}</style></head><body>"]
tableau, code = [], False
def flush():
    global tableau
    if tableau:
        out.append("<table>")
        for i, rang in enumerate(tableau):
            cellules = [c.strip() for c in rang.strip("|").split("|")]
            balise = "th" if i == 0 else "td"
            out.append("<tr>" + "".join(f"<{balise}>{c}</{balise}>" for c in cellules) + "</tr>")
        out.append("</table>")
        tableau = []
def inline(s):
    s = h.escape(s)
    s = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", s)
    s = re.sub(r"`(.+?)`", r"<code>\1</code>", s)
    s = re.sub(r"\[(.+?)\]\((.+?)\)", r"<a href='\2'>\1</a>", s)
    return s
for l in lignes:
    if l.startswith("```"):
        code = not code
        out.append("<pre>" if code else "</pre>")
        continue
    if code:
        out.append(h.escape(l))
        continue
    if l.startswith("|") and "---" not in l:
        tableau.append(l)
        continue
    if l.startswith("|"):
        continue
    flush()
    if l.startswith("# "):    out.append(f"<h1>{inline(l[2:])}</h1>")
    elif l.startswith("## "): out.append(f"<h2>{inline(l[3:])}</h2>")
    elif l.startswith("### "):out.append(f"<h3>{inline(l[4:])}</h3>")
    elif l.startswith("- ") or l.startswith("* "): out.append(f"<p>&bull; {inline(l[2:])}</p>")
    elif l.startswith("> "):  out.append(f"<p style='color:#555;border-left:3px solid #999;padding-left:10px'>{inline(l[2:])}</p>")
    elif l.strip():           out.append(f"<p>{inline(l)}</p>")
flush()
out.append("</body></html>")
print("\n".join(out))
PY
  textutil -convert docx "$html" -output "$docx"
  rm -f "$html"
  echo "  $docx"
}

if [[ $# -gt 0 ]]; then
  for f in "$@"; do convertir "$f"; done
else
  for f in docs/roadmap/14_REGLES_GIT.md docs/roadmap/12_PROCEDURE_DEPLOIEMENT.md docs/roadmap/13_PLAN_ACTUALISE_10_AOUT.md docs/roadmap/recette/RECETTE_L4.md; do
    convertir "$f"
  done
fi
