#!/usr/bin/env bash
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
CGU_DIR="$SCRIPT_DIR/../public/cgu"
MD_FILE="$CGU_DIR/cgu.md"
DATE=$(date +%d-%m-%Y)
PDF_FILE="$CGU_DIR/cgu-confidentialite-oki-$DATE.pdf"
TMP_HTML=$(mktemp /tmp/cgu-XXXXXX.html)

trap 'rm -f "$TMP_HTML"' EXIT

cat > "$TMP_HTML" <<'HTML_HEAD'
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>CGU et politique de confidentialité — PAWÒL-NU</title>
<style>
  body { font-family: "Segoe UI", Arial, sans-serif; font-size: 13px; color: #222; max-width: 800px; margin: 40px auto; padding: 0 30px; line-height: 1.6; text-align: justify; }
  h1 { font-size: 20px; margin-bottom: 4px; }
  h2 { font-size: 16px; margin-top: 28px; margin-bottom: 6px; border-bottom: 1px solid #ccc; padding-bottom: 4px; }
  h3 { font-size: 14px; margin-top: 18px; margin-bottom: 4px; }
  p  { margin: 8px 0; }
  ul { margin: 6px 0 6px 20px; padding: 0; }
  li { margin: 4px 0; }
  a  { color: #1a73e8; text-decoration: none; }
  hr { border: none; border-top: 1px solid #ddd; margin: 32px 0; }
  em { color: #888; font-size: 11px; }
</style>
</head>
<body>
HTML_HEAD

node - "$MD_FILE" >> "$TMP_HTML" <<'NODE_EOF'
const fs = require('fs')
const md = fs.readFileSync(process.argv[2], 'utf8')

let html = md
  .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
  .replace(/^# (.+)$/gm, '<h1>$1</h1>')
  .replace(/^## (.+)$/gm, '<h2>$1</h2>')
  .replace(/^### (.+)$/gm, '<h3>$1</h3>')
  .replace(/^\*\*\*(.+)\*\*\*$/gm, '<hr>')
  .replace(/^---$/gm, '<hr>')
  .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
  .replace(/\*(.+?)\*/g, '<em>$1</em>')
  .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>')
  .replace(/^- (.+)$/gm, '<li>$1</li>')
  .replace(/(<li>.*<\/li>\n?)+/gs, m => `<ul>${m}</ul>`)
  .replace(/\n\n/g, '</p><p>')
  .replace(/^(?!<[hup]|<\/[hup]|<li|<\/li|<ul|<\/ul|<hr)(.+)$/gm, '$1')

process.stdout.write(`<p>${html}</p>`)
NODE_EOF

echo '</body></html>' >> "$TMP_HTML"

chromium --headless --no-sandbox --no-pdf-header-footer \
  --print-to-pdf="$PDF_FILE" "$TMP_HTML" 2>/dev/null

echo "PDF généré : $PDF_FILE"
echo "Pense à mettre à jour NEXT_PUBLIC_CGU_DOWNLOAD_LINK=/cgu/$(basename "$PDF_FILE")"
