#!/usr/bin/env bash
# ---------------------------------------------------------------------------
# build_docs.sh — Local documentation build helper for ut-arr
#
# Usage:
#   ./build_docs.sh              Build HTML (default)
#   ./build_docs.sh html         Build HTML
#   ./build_docs.sh pdf          Build PDF via rst2pdf
#   ./build_docs.sh latexpdf     Build PDF via LaTeX
#   ./build_docs.sh epub         Build EPUB
#   ./build_docs.sh docx         Build DOCX via pandoc
#   ./build_docs.sh text         Build plain text
#   ./build_docs.sh man          Build man pages
#   ./build_docs.sh all          Build all formats
#   ./build_docs.sh clean        Remove build artefacts
#   ./build_docs.sh install-deps Install build dependencies
#   ./build_docs.sh formats      List valid build formats
# ---------------------------------------------------------------------------
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DOCS_DIR="${SCRIPT_DIR}/../docs"
BUILD_DIR="${DOCS_DIR}/_build"

# Colours (disabled when piped)
if [ -t 1 ]; then
    GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; NC='\033[0m'
else
    GREEN=''; YELLOW=''; RED=''; NC=''
fi

info()  { echo -e "${GREEN}[INFO]${NC}  $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC}  $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }

# ---- helpers ---------------------------------------------------------------

ensure_deps() {
    if ! python3 -c "import sphinx" 2>/dev/null; then
        info "Installing build dependencies ..."
        python3 -m pip install --user --quiet --upgrade pip
        python3 -m pip install --user --quiet -r "${DOCS_DIR}/requirements.txt"
    fi
}

check_tool() {
    if ! command -v "$1" &>/dev/null; then
        error "'$1' is not installed.  $2"
        return 1
    fi
}

# ---- build targets ---------------------------------------------------------

do_clean() {
    info "Cleaning ${BUILD_DIR} ..."
    rm -rf "${BUILD_DIR}"
    info "Clean complete."
}

do_html() {
    ensure_deps
    info "Building HTML ..."
    sphinx-build -M html "${DOCS_DIR}" "${BUILD_DIR}" -W --keep-going 2>&1 || true
    info "HTML ready: ${BUILD_DIR}/html/index.html"
}

do_pdf() {
    ensure_deps
    check_tool rst2pdf "Install rst2pdf: pip install rst2pdf" || return 1
    info "Building PDF (rst2pdf) ..."
    sphinx-build -M pdf "${DOCS_DIR}" "${BUILD_DIR}" 2>&1 || true
    info "PDF ready: ${BUILD_DIR}/pdf/"
}

do_latexpdf() {
    ensure_deps
    check_tool pdflatex "Install a TeX distribution (texlive-full or miktex)." || return 1
    info "Building PDF (LaTeX) ..."
    sphinx-build -M latexpdf "${DOCS_DIR}" "${BUILD_DIR}" 2>&1 || true
    info "PDF ready: ${BUILD_DIR}/latex/ut-arr.pdf"
}

do_epub() {
    ensure_deps
    info "Building EPUB ..."
    sphinx-build -M epub "${DOCS_DIR}" "${BUILD_DIR}" 2>&1 || true
    info "EPUB ready: ${BUILD_DIR}/epub/ut-arr.epub"
}

do_docx() {
    ensure_deps
    check_tool pandoc "Install pandoc: https://pandoc.org/installing.html" || return 1
    info "Building single-page HTML for DOCX conversion ..."
    sphinx-build -M singlehtml "${DOCS_DIR}" "${BUILD_DIR}" 2>&1 || true
    info "Converting to DOCX via pandoc ..."
    pandoc "${BUILD_DIR}/singlehtml/index.html" \
        --from html --to docx \
        -o "${BUILD_DIR}/ut-arr.docx" \
        --metadata title="ut-arr Documentation"
    info "DOCX ready: ${BUILD_DIR}/ut-arr.docx"
}

do_text() {
    ensure_deps
    info "Building plain text ..."
    sphinx-build -M text "${DOCS_DIR}" "${BUILD_DIR}" 2>&1 || true
    info "Text ready: ${BUILD_DIR}/text/"
}

do_man() {
    ensure_deps
    info "Building man pages ..."
    sphinx-build -M man "${DOCS_DIR}" "${BUILD_DIR}" 2>&1 || true
    info "Man pages ready: ${BUILD_DIR}/man/"
}

do_install_deps() {
    info "Installing / upgrading build dependencies ..."
    python3 -m pip install --user --upgrade pip
    python3 -m pip install --user --upgrade -r "${DOCS_DIR}/requirements.txt"
    info "Dependencies installed."
}

do_all() {
    do_html
    do_pdf
    do_latexpdf
    do_epub
    do_docx
    do_man
    info "All formats built in ${BUILD_DIR}/"
}

do_formats() {
    echo "Valid build formats:"
    echo ""
    echo "  html          HTML documentation"
    echo "  pdf           PDF via rst2pdf"
    echo "  latexpdf      PDF via LaTeX"
    echo "  epub          EPUB e-book"
    echo "  docx          Word document (requires pandoc)"
    echo "  text          Plain text"
    echo "  man           Man pages"
    echo ""
    echo "Multiple formats can be built by running the script once per format,"
    echo "or use 'all' to build all formats at once."
}

# ---- main ------------------------------------------------------------------

TARGET="${1:-html}"

case "${TARGET}" in
    html)         do_html         ;;
    pdf)          do_pdf          ;;
    latexpdf)     do_latexpdf     ;;
    epub)         do_epub         ;;
    docx)         do_docx         ;;
    text)         do_text         ;;
    man)          do_man          ;;
    all)          do_all          ;;
    clean)        do_clean        ;;
    install-deps) do_install_deps ;;
    formats)      do_formats      ;;
    -h|--help|help)
        echo "Usage: $0 {html|pdf|latexpdf|epub|docx|text|man|all|clean|install-deps|formats}"
        echo ""
        echo "Format targets:"
        echo "  html          Build HTML documentation (default)"
        echo "  pdf           Build PDF via rst2pdf"
        echo "  latexpdf      Build PDF via LaTeX"
        echo "  epub          Build EPUB e-book"
        echo "  docx          Build DOCX via pandoc"
        echo "  text          Build plain text"
        echo "  man           Build man pages"
        echo ""
        echo "Combo targets:"
        echo "  all           Build all formats (html, pdf, latexpdf, epub, docx, man)"
        echo ""
        echo "Utility targets:"
        echo "  clean         Remove all build artefacts"
        echo "  install-deps  Install Python dependencies (pip --user)"
        echo "  formats       List valid build formats"
        ;;
    *)
        error "Unknown target: ${TARGET}"
        echo "Run '$0 --help' for usage."
        exit 1
        ;;
esac
