#!/usr/bin/env bash
# Generate a PDF from the modular resume HTML (US Letter via CSS @page).
# Requires Google Chrome. Run from anywhere:
#   bash "/Users/nate/docs/40-personal/resume/print-resume-pdf.sh"
# Optional first argument: HTML filename in this directory (default: healthcare-resume-modular-new.html).
# Examples:
#   bash .../print-resume-pdf.sh
#   bash .../print-resume-pdf.sh healthcare-resume-modular.html

set -euo pipefail
DIR="$(cd "$(dirname "$0")" && pwd)"
HTML_FILE="${1:-Nathan-Walker-Resume-EXL-CX-CCaaS-AI-Transformation-Lead-modular.html}"
HTML_PATH="${DIR}/${HTML_FILE}"
OUT="${DIR}/${HTML_FILE%.html}.pdf"

CHROME=""
for c in \
  "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" \
  "/Applications/Chromium.app/Contents/MacOS/Chromium" \
  "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"
do
  if [[ -x "$c" ]]; then CHROME="$c"; break; fi
done

if [[ -z "$CHROME" ]]; then
  echo "Install Google Chrome (or Chromium/Edge) to print this resume to PDF." >&2
  exit 1
fi

if [[ ! -f "$HTML_PATH" ]]; then
  echo "Resume HTML not found: $HTML_PATH" >&2
  exit 1
fi

PORT="${RESUME_HTTP_PORT:-9844}"

cleanup() {
  if [[ -n "${SERVER_PID:-}" ]] && kill -0 "$SERVER_PID" 2>/dev/null; then
    kill "$SERVER_PID" 2>/dev/null || true
    wait "$SERVER_PID" 2>/dev/null || true
  fi
}
trap cleanup EXIT

# HTTP avoids headless Chrome quirks with file:// + remote fonts.
(cd "$DIR" && python3 -m http.server "$PORT" >/dev/null 2>&1) &
SERVER_PID=$!
sleep 0.8

"$CHROME" \
  --headless=new \
  --disable-gpu \
  --disable-dev-shm-usage \
  --no-first-run \
  --no-pdf-header-footer \
  --run-all-compositor-stages-before-draw \
  --virtual-time-budget=25000 \
  --print-to-pdf="$OUT" \
  "http://127.0.0.1:${PORT}/${HTML_FILE}"

echo "Wrote $OUT"
