#!/usr/bin/env bash

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

check_only=false
if [[ "${1:-}" == "--check-only" ]]; then
  check_only=true
elif [[ $# -gt 0 ]]; then
  printf 'usage: %s [--check-only]\n' "$0" >&2
  exit 2
fi

missing="$(missing_tools)"
if [[ -z "${missing}" ]]; then
  if ! check_tool_versions; then
    printf 'Installed tools are too old. Upgrade them, then run `make doctor`.\n' >&2
    printf 'On macOS: brew upgrade pandoc typst go\n' >&2
    exit 1
  fi
  if ! has_supported_cjk_font; then
    printf '%s\n' 'No supported Simplified Chinese font was found.' >&2
    if [[ "$(uname -s)" != "Darwin" ]]; then
      printf '%s\n' \
        'Install Noto Serif CJK SC or Source Han Serif SC, then run `make doctor`.' >&2
      exit 1
    fi
    missing="cjk-font"
  fi
fi

if [[ -z "${missing}" ]]; then
  printf 'Book toolchain is ready.\n'
  pandoc --version | sed -n '1p'
  typst --version
  python3 --version
  go version
  exit 0
fi

printf 'Missing required book tools:\n%s\n' "${missing}" >&2
if [[ "${check_only}" == true ]]; then
  exit 1
fi

case "$(uname -s)" in
  Darwin)
    if ! command -v brew >/dev/null 2>&1; then
      printf '%s\n' 'Homebrew is not installed. Install it from https://brew.sh, then run `make bootstrap` again.' >&2
      exit 1
    fi
    printf '%s\n' 'The following command installs only the declared book tools:' >&2
    printf '  brew bundle --file=%q\n' "${INFRA_DIR}/Brewfile" >&2
    if [[ ! -t 0 ]]; then
      printf '%s\n' 'Non-interactive shell detected; no system changes were made.' >&2
      exit 1
    fi
    read -r -p 'Run this Homebrew command now? [y/N] ' answer
    case "${answer}" in
      y|Y|yes|YES)
        exec brew bundle --file="${INFRA_DIR}/Brewfile"
        ;;
      *)
        printf '%s\n' 'No system changes were made.' >&2
        exit 1
        ;;
    esac
    ;;
  Linux)
    printf '%s\n' 'Install Pandoc, Typst, Python 3, and Go 1.25+ with your system package manager, then run `make doctor`.' >&2
    printf '%s\n' 'Official downloads: https://pandoc.org/installing.html, https://github.com/typst/typst/releases, and https://go.dev/dl/' >&2
    exit 1
    ;;
  *)
    printf '%s\n' 'Install Pandoc, Typst, Python 3, and Go 1.25+, then run `make doctor`.' >&2
    exit 1
    ;;
esac
