#!/usr/bin/env bash
# Generates the Hugo legal pages from docs/legal/ — the single source of truth.
# Each doc's first "# Heading" becomes the page title (and is stripped from the
# body so it isn't rendered twice). Run from site/ whenever the legal docs change:
#   ./build-legal.sh
# The generated content/legal/<slug>.<lang>.md files are committed so the Docker
# build only needs site/.
set -euo pipefail

site_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
legal_src="$(cd "$site_dir/../docs/legal" && pwd)"
out="$site_dir/content/legal"

# slug | English master | Spanish mirror | menu weight
rows=(
  "privacy|privacy-policy.md|politica-de-privacidad.md|1"
  "terms|terms-of-use.md|condiciones-de-uso.md|2"
  "rules|community-rules.md|normas-de-la-comunidad.md|3"
  "seeds|seed-legality-notice.md|aviso-sobre-semillas.md|4"
)

emit() { # <src-md> <out-md> <slug> <weight>
  local src="$1" dst="$2" slug="$3" weight="$4"
  # First "# ..." line -> title; everything after that line -> body. Strip a
  # leading "Tane — " so it doesn't collide with the site title suffix in <title>.
  local title
  title="$(sed -n 's/^# \(.*\)/\1/p' "$src" | head -n1 \
    | sed -E 's/^Tane[[:space:]]*(—|–|-)[[:space:]]*//')"
  {
    printf -- '---\n'
    printf 'title: "%s"\n' "${title//\"/\\\"}"
    printf 'slug: "%s"\n' "$slug"
    printf 'weight: %s\n' "$weight"
    printf 'translationKey: "legal-%s"\n' "$slug"
    printf -- '---\n\n'
    # Drop the first H1 line, keep the rest verbatim.
    awk 'NR==1 && /^# /{next} {print}' "$src"
  } > "$dst"
  echo "  $(basename "$dst")  <-  $(basename "$src")"
}

for row in "${rows[@]}"; do
  IFS='|' read -r slug en es weight <<<"$row"
  emit "$legal_src/$en"    "$out/$slug.en.md" "$slug" "$weight"
  emit "$legal_src/es/$es" "$out/$slug.es.md" "$slug" "$weight"
done

echo "Generated legal pages in $out"

# --- Plain-language "About" page, generated from the docs/ explainers ---------
# Each page uses its own fixed title (not the doc's H1) and drops the first H1.
docs_dir="$(cd "$site_dir/../docs" && pwd)"
emit_about() { # <src-md> <out-md> <title> <description>
  local src="$1" dst="$2" title="$3" desc="$4"
  [[ -f "$src" ]] || return 0
  {
    printf -- '---\n'
    printf 'title: "%s"\n' "$title"
    printf 'slug: "about"\n'
    printf 'translationKey: "about"\n'
    printf 'description: "%s"\n' "$desc"
    printf -- '---\n\n'
    awk 'NR==1 && /^# /{next} {print}' "$src"
  } > "$dst"
  echo "Generated $(basename "$dst")  <-  $(basename "$src")"
}

emit_about "$docs_dir/que-es-tane.md"  "$site_dir/content/about.es.md" \
  "Qué es Tane" "Tane explicada para todos los públicos."
emit_about "$docs_dir/what-is-tane.md" "$site_dir/content/about.en.md" \
  "What is Tane" "Tane explained for everyone."
