#!/usr/bin/env bash
# export_analysis_pdfs
# ---------------------
# Pipeline que exporta todos los notebooks de un analisis a PDF.
# Compone: assert_command_exists + install_nbconvert + notebook_to_pdf
#
# USO:
#   ./export_analysis_pdfs.sh <nombre_analysis> [pattern]
#
# EJEMPLOS:
#   ./export_analysis_pdfs.sh finanzas
#   ./export_analysis_pdfs.sh ml "notebooks/01_*.ipynb"

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REGISTRY_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"

# Source funciones atomicas
source "$REGISTRY_ROOT/bash/functions/shell/assert_command_exists.sh"
source "$REGISTRY_ROOT/bash/functions/infra/install_nbconvert.sh"
source "$REGISTRY_ROOT/bash/functions/infra/notebook_to_pdf.sh"

# ── Argumentos ──────────────────────────────────────────────

NOMBRE="${1:-}"
if [ -z "$NOMBRE" ]; then
    echo "Uso: $0 <nombre_analysis> [pattern]" >&2
    echo "  Ejemplo: $0 finanzas" >&2
    echo "  Ejemplo: $0 ml 'notebooks/01_*.ipynb'" >&2
    exit 1
fi
shift
PATTERN="${1:-notebooks/*.ipynb}"

ANALYSIS_DIR="${REGISTRY_ROOT}/analysis/${NOMBRE}"

# Verificar que el analysis existe
if [ ! -d "$ANALYSIS_DIR" ]; then
    echo "Error: analysis '${NOMBRE}' no existe en ${ANALYSIS_DIR}" >&2
    exit 1
fi

echo ""
echo "════════════════════════════════════════════════════════════"
echo "  EXPORT ANALYSIS PDFs: ${NOMBRE}"
echo "  Directorio: ${ANALYSIS_DIR}"
echo "════════════════════════════════════════════════════════════"
echo ""

# ── 1. Verificar herramientas ───────────────────────────────

echo "[1/3] Verificando herramientas..."
assert_command_exists uv
echo "  OK"

# ── 2. Instalar nbconvert + playwright ──────────────────────

echo "[2/3] Instalando dependencias de exportacion..."
install_nbconvert "$ANALYSIS_DIR"
echo "  OK"

# ── 3. Convertir notebooks a PDF ────────────────────────────

echo "[3/3] Convirtiendo notebooks a PDF..."
notebook_to_pdf "$ANALYSIS_DIR" "$PATTERN"

# ── Resumen ─────────────────────────────────────────────────

echo ""
echo "════════════════════════════════════════════════════════════"
echo "  EXPORT COMPLETADO"
echo "════════════════════════════════════════════════════════════"
