#!/usr/bin/env bash

set -euo pipefail
source "$(dirname "$0")/common.sh"
ensure_book_context
require_tools

BUILD_DIR="${BOOK_DIR}/build"
DIST_DIR="${BOOK_DIR}/dist"
BOOKS_ROOT="$(cd "${BOOK_DIR}/.." && pwd)"
THEME_DIR="${BOOK_DIR}/theme"
if [[ ! -d "${THEME_DIR}" ]]; then
  THEME_DIR="${INFRA_DIR}/theme"
fi
THEME_TEMPLATE="${THEME_DIR}/book.typ"
THEME_TEMPLATE_RELATIVE="$(
  python3 -c 'import os, sys; print(os.path.relpath(sys.argv[1], sys.argv[2]))' \
    "${THEME_TEMPLATE}" "${BUILD_DIR}"
)"

select_font() {
  local family
  for family in "$@"; do
    if grep -Fqx -- "${family}" <<<"${AVAILABLE_FONTS}"; then
      printf '%s\n' "${family}"
      return 0
    fi
  done
  return 1
}

AVAILABLE_FONTS="$(typst fonts)"
body_font="$(select_font \
  'Noto Serif CJK SC' 'Source Han Serif SC' 'Songti SC' \
  'Noto Sans CJK SC' 'Source Han Sans SC' 'PingFang SC')" || {
  printf '%s\n' 'No supported Simplified Chinese font was found.' >&2
  printf '%s\n' 'Install Noto Serif CJK SC or Source Han Serif SC, then rerun make.' >&2
  exit 1
}
sans_font="$(select_font \
  'Noto Sans CJK SC' 'Source Han Sans SC' 'PingFang SC' \
  'Noto Serif CJK SC' 'Songti SC')" || {
  printf '%s\n' 'No supported Simplified Chinese sans-serif font was found.' >&2
  exit 1
}
mono_font="$(select_font 'JetBrains Mono' 'Noto Sans Mono CJK SC' 'Menlo' 'DejaVu Sans Mono')" || {
  printf '%s\n' 'No supported monospace font was found.' >&2
  exit 1
}

mkdir -p "${BUILD_DIR}" "${DIST_DIR}"
chapters=()
while IFS= read -r chapter; do
  chapters+=("${chapter}")
done < <(python3 "${INFRA_DIR}/scripts/summary.py" --book-dir "${BOOK_DIR}")

print_profile="${BOOK_PRINT_PROFILE:-a4}"
case "${print_profile}" in
  a4)
    paper_size="a4"
    font_size="10.5pt"
    output_pdf="${DIST_DIR}/${BOOK_SLUG}.pdf"
    ;;
  b5-proof)
    paper_size="iso-b5"
    font_size="11pt"
    output_pdf="${DIST_DIR}/${BOOK_SLUG}-b5-proof.pdf"
    ;;
  *)
    printf 'Unsupported BOOK_PRINT_PROFILE: %s\n' "${print_profile}" >&2
    exit 1
    ;;
esac

pandoc \
  --from=markdown+yaml_metadata_block+fenced_divs+link_attributes+rebase_relative_paths \
  --to=typst \
  --standalone \
  --metadata-file="${BOOK_DIR}/book.yaml" \
  --lua-filter="${INFRA_DIR}/scripts/book-structure.lua" \
  --lua-filter="${INFRA_DIR}/scripts/normalize-media.lua" \
  --template="${THEME_DIR}/pandoc.typst" \
  --resource-path="${BOOK_DIR}:${INFRA_DIR}" \
  --top-level-division=chapter \
  --syntax-highlighting=tango \
  -V "template=${THEME_TEMPLATE_RELATIVE}" \
  -V toc=true \
  -V toc-depth=3 \
  -V page-numbering=1 \
  -V papersize="${paper_size}" \
  -V fontsize="${font_size}" \
  "${chapters[@]}" \
  --output="${BUILD_DIR}/${BOOK_SLUG}.typ"

python3 - <<'PY' "${BUILD_DIR}/${BOOK_SLUG}.typ" "${BOOK_SLUG}"
from pathlib import Path
import sys

typ_path = Path(sys.argv[1])
book_slug = sys.argv[2]
text = typ_path.read_text(encoding="utf-8")
text = text.replace('image("/manuscript/', f'image("/{book_slug}/manuscript/')
typ_path.write_text(text, encoding="utf-8")
PY

typst_dep_args=(--make-deps="${BUILD_DIR}/${BOOK_SLUG}.d")
if typst compile --help 2>/dev/null | grep -q -- '--deps <PATH>'; then
  typst_dep_args=(--deps="${BUILD_DIR}/${BOOK_SLUG}.d" --deps-format=make)
fi

typst compile \
  --root="${BOOKS_ROOT}" \
  "${typst_dep_args[@]}" \
  --input="body-font=${body_font}" \
  --input="sans-font=${sans_font}" \
  --input="mono-font=${mono_font}" \
  --input="print-profile=${print_profile}" \
  "${BUILD_DIR}/${BOOK_SLUG}.typ" \
  "${output_pdf}"

size="$(du -h "${output_pdf}" | awk '{print $1}')"
printf 'Built %s (%s).\n' "${output_pdf}" "${size}"
