#!/usr/bin/env bash
# Smoke test for the five server-side PDF tools.
# Run from the project/ directory: bash test_pdf_tools.sh
set -e

PASS=0
FAIL=0

check() {
  local name="$1"; local cmd="$2"
  if eval "$cmd" >/dev/null 2>&1; then
    echo "  PASS: $name"; PASS=$((PASS+1))
  else
    echo "  FAIL: $name"; FAIL=$((FAIL+1))
  fi
}

echo "=== PDF Tools Smoke Test ==="

# 1. LibreOffice binary available
check "libreoffice in PATH" "libreoffice --headless --version"

# 2. Five tools NOT present inside the client_side_tools block of filetypes.py.
#    Extract only lines between "client_side_tools" and the closing "]," so we
#    do not accidentally match the server_side_tools block below it.
CLIENT_SIDE_BLOCK=$(awk '/"client_side_tools"/{found=1} found && /\],/{found=0; print; next} found{print}' configs/filetypes.py)
for tool in "word-to-pdf" "powerpoint-to-pdf" "excel-to-pdf" "pdf-to-word" "pdf-to-powerpoint"; do
  if echo "$CLIENT_SIDE_BLOCK" | grep -q "\"${tool}\""; then
    echo "  FAIL: $tool must NOT be in client_side_tools (routing bug)"; FAIL=$((FAIL+1))
  else
    echo "  PASS: $tool is not in client_side_tools"; PASS=$((PASS+1))
  fi
done

# 3. LibreOffice basic conversion works (txt -> pdf)
echo "LibreOffice smoke test" > /tmp/_pdf_smoke.txt
check "libreoffice txt-to-pdf" \
  "libreoffice --headless --norestore --convert-to pdf --outdir /tmp /tmp/_pdf_smoke.txt && test -f /tmp/_pdf_smoke.pdf"
rm -f /tmp/_pdf_smoke.txt /tmp/_pdf_smoke.pdf

# 4. Error message contract: missing binary raises correct message
check "_find_libreoffice error message" \
  "grep -q 'LibreOffice is not installed on this server' converters/pdf_converter.py"

echo ""
echo "Results: $PASS passed, $FAIL failed"
[ "$FAIL" -eq 0 ]
