#!/bin/bash

# build.sh — convierte todos los .md a .html y actualiza el index.html

TEMPLATE="template.html"
INDEX="index.html"
SKIP="acerca"   # excluye archivos .md que no son notas
OK=0
FAIL=0

# ── 1. Convertir cada .md a .html ─────

for f in *.md; do
  slug="${f%.md}"

  # saltar archivos que no son notas
  skip=false
  for s in $SKIP; do
    [[ "$slug" == "$s" ]] && skip=true
  done
  $skip && continue

  output="${slug}.html"
  if pandoc "$f" --template "$TEMPLATE" -o "$output"; then
    echo "  ok  $f → $output"
    OK=$((OK + 1))
  else
    echo "  error  $f"
    FAIL=$((FAIL + 1))
  fi
done

echo ""
echo "$OK convertido(s), $FAIL error(es)"
echo ""

# ── 2. Reconstruir el bloque de entradas en index.html ──────

echo "actualizando $INDEX..."

# recolectar entradas: "fecha^titulo^slug"
entries=()
for f in *.md; do
  slug="${f%.md}"

  skip=false
  for s in $SKIP; do
    [[ "$slug" == "$s" ]] && skip=true
  done
  $skip && continue

  title=$(grep -m1 '^title:' "$f" | sed 's/^title:[[:space:]]*//' | tr -d '"')
  date=$(grep -m1 '^date:'  "$f" | sed 's/^date:[[:space:]]*//'  | tr -d '"')

  [[ -z "$title" ]] && title="$slug"
  [[ -z "$date"  ]] && date=""

  # separador de un solo carácter para que IFS funcione correctamente
  entries+=("${date}^${title}^${slug}")
done

# ordenar por fecha descendente
IFS=$'\n' sorted=($(sort -r <<<"${entries[*]}")); unset IFS

# construir el bloque HTML
block=""
total=${#sorted[@]}
num=$total
for entry in "${sorted[@]}"; do
  IFS="^" read -r date title slug <<< "$entry"
  padded=$(printf "%02d" $num)
  block+="      <a class=\"index-line\" href=\"${slug}.html\">\n"
  block+="        <span class=\"num\">${padded}</span>\n"
  block+="        <span class=\"title\">${title}</span>\n"
  block+="        <span class=\"date\">${date}</span>\n"
  block+="      </a>\n"
  num=$((num - 1))
done

# reemplazar entre marcadores en index.html
python3 - "$INDEX" "$block" <<'EOF'
import sys, re

path  = sys.argv[1]
block = sys.argv[2]

with open(path, "r") as fh:
    content = fh.read()

new_content = re.sub(
    r'<!-- ENTRADAS -->.*?<!-- /ENTRADAS -->',
    '<!-- ENTRADAS -->\n' + block + '<!-- /ENTRADAS -->',
    content,
    flags=re.DOTALL
)

with open(path, "w") as fh:
    fh.write(new_content)

print("  ok  index.html actualizado con", block.count("index-line"), "entrada(s)")
EOF
