#!/usr/bin/env bash
# Build a CV variant: profile/<src>.yaml -> profile/<base>.html -> PDF in inbox.
# Usage:
#   bash profile/build-western-cv-pdf.sh                          # master EN CV (cv.yaml)
#   bash profile/build-western-cv-pdf.sh profile/cv-ru-lead.yaml  # any other variant
# The PDF gets a full timestamp and lands in /mnt/storage/inbox (visible via
# https://files.udalovs.ru). Previous versions stay in the inbox; the build
# time is embedded in the PDF footer.
set -euo pipefail

cd "$(dirname "$0")"

SRC_YAML="$(basename "${1:-cv.yaml}")"
if [ "$SRC_YAML" = "cv.yaml" ]; then
  BASE="western-cv-template"
else
  BASE="${SRC_YAML%.yaml}"
fi
INBOX="${INBOX:-/mnt/storage/inbox}"

# 1) regenerate HTML + Markdown + TXT from the single source
python3 cv-build.py --src "$SRC_YAML"

STAMP="$(date +%Y%m%d-%H%M%S)"                # full timestamp, e.g. 20260907-185612
GEN="$(date -u +'%Y-%m-%d %H:%M:%S UTC')"     # human-readable build time
OUT="${BASE}-${STAMP}.pdf"

# 2) inject build time into the HTML
TMP="$(mktemp --suffix=.html)"
sed "s/__GEN_STAMP__/${GEN}/" "${BASE}.html" > "$TMP"

# 3) render PDF directly to inbox (no local copy — never commit binaries)
playwright pdf --paper-format A4 "file://$(realpath "$TMP")" "$INBOX/${OUT}"

# 4) stable "latest" copy
cp -f "$INBOX/${OUT}" "$INBOX/${BASE}.pdf"

rm -f "$TMP"

echo "OK:"
echo "  inbox : $INBOX/${OUT}"
echo "  latest: $INBOX/${BASE}.pdf"
echo "  web   : https://files.udalovs.ru/${OUT}"