#!/usr/bin/env bash
# In Motion Automation — HTML to PDF
# Usage:
#   ./export.sh path/to/doc.html
#   ./export.sh path/to/doc.html out.pdf
#   ./export.sh path/to/doc.html --landscape          # A4 landscape (client decks) — do NOT use for research/decision
#   ./export.sh path/to/doc.html --letter
#   ./export.sh path/to/doc.html out.pdf --deck-16x9  # TRUE 16:9 (13.333in × 7.5in) research/decision decks
#
# Deck mode prefers Playwright page.pdf({width,height}) because Chrome
# --print-to-pdf often ignores CSS @page and emits A4/Letter.
set -euo pipefail

CHROME="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"

if [[ $# -lt 1 ]]; then
  echo "usage: $0 file.html [out.pdf] [--landscape] [--letter] [--deck-16x9]" >&2
  exit 1
fi

SRC=""; OUT=""; LANDSCAPE=0; LETTER=0; DECK16=0
for arg in "$@"; do
  case "$arg" in
    --landscape) LANDSCAPE=1 ;;
    --letter) LETTER=1 ;;
    --deck-16x9) DECK16=1 ;;
    --*) echo "unknown flag: $arg" >&2; exit 1 ;;
    *)
      if [[ -z "$SRC" ]]; then SRC="$arg"
      elif [[ -z "$OUT" ]]; then OUT="$arg"
      else echo "unexpected: $arg" >&2; exit 1
      fi
      ;;
  esac
done

[[ -f "$SRC" ]] || { echo "not a file: $SRC" >&2; exit 1; }
ABS="$(cd "$(dirname "$SRC")" && pwd)/$(basename "$SRC")"
if [[ -z "$OUT" ]]; then OUT="${ABS%.*}.pdf"
elif [[ "$OUT" != /* ]]; then OUT="$(pwd)/$OUT"
fi

if [[ "$DECK16" -eq 1 ]]; then
  echo "deck-16x9: exporting 13.333in × 7.5in (NOT A4)"
  if node -e "require('playwright')" 2>/dev/null; then
    node << NODE
const { chromium } = require('playwright');
(async () => {
  const browser = await chromium.launch({ headless: true });
  const page = await browser.newPage();
  await page.goto('file://$ABS', { waitUntil: 'networkidle', timeout: 60000 });
  await page.evaluate(async () => { try { await document.fonts.ready; } catch (e) {} });
  await page.waitForTimeout(800);
  await page.pdf({
    path: '$OUT',
    width: '13.333in',
    height: '7.5in',
    printBackground: true,
    margin: { top: '0', right: '0', bottom: '0', left: '0' },
    preferCSSPageSize: false,
  });
  await browser.close();
  console.log('wrote $OUT');
})().catch((e) => { console.error(e); process.exit(1); });
NODE
  else
    echo "playwright not found in node; falling back to Chrome --print-to-pdf (may ignore @page)" >&2
    [[ -x "$CHROME" ]] || { echo "Google Chrome not found at $CHROME" >&2; exit 1; }
    "$CHROME" --headless=new --disable-gpu --no-pdf-header-footer --no-margins \
      --virtual-time-budget=10000 --print-to-pdf="$OUT" --print-to-pdf-no-header "file://$ABS"
    echo "wrote $OUT (Chrome fallback — verify 13.333×7.5in)"
  fi
  exit 0
fi

# Client stationery / A4 (or Letter) path — headless Chrome
[[ -x "$CHROME" ]] || { echo "Google Chrome not found at $CHROME" >&2; exit 1; }

if [[ "$LETTER" -eq 1 ]]; then
  PAPER_W="8.5in"; PAPER_H="11in"
else
  PAPER_W="210mm"; PAPER_H="297mm"
fi
if [[ "$LANDSCAPE" -eq 1 ]]; then
  TMP_W="$PAPER_W"; PAPER_W="$PAPER_H"; PAPER_H="$TMP_W"
fi

"$CHROME" \
  --headless=new \
  --disable-gpu \
  --no-pdf-header-footer \
  --no-margins \
  --virtual-time-budget=10000 \
  --print-to-pdf="$OUT" \
  --print-to-pdf-no-header \
  "file://$ABS"

echo "wrote $OUT"
echo "paper ${PAPER_W} × ${PAPER_H} (CSS @page in the HTML is authoritative)"
