#!/usr/bin/env bash

# Changelog:
# 2024-10-03 - Initial version
#            - Added error handling, usage information, and best practices
#            - Improved variable naming and quoting
#            - Added cleanup function to remove temporary file

set -euo pipefail

# Script description:
# This script fetches "On This Day" historical events from the BBC website
# for the current date and displays them.

# Global readonly variables
readonly SCRIPT_NAME="${0##*/}"
readonly BBC_URL="http://news.bbc.co.uk/onthisday/low/dates/stories"

# Function to display usage information
usage() {
  cat <<EOF
Usage: ${SCRIPT_NAME} [OPTIONS]

Options:
  -h, --help    Display this help message and exit

This script fetches and displays historical events for the current date from the BBC website.
EOF
}

# Function to clean up temporary files
cleanup() {
  if [[ -f "${TEMP_FILE}" ]]; then
    rm -f "${TEMP_FILE}"
  fi
}

# Main function
main() {
  local month_name
  local day_of_month

  # Process command-line arguments
  if [[ "${1:-}" == "-h" ]] || [[ "${1:-}" == "--help" ]]; then
    usage
    exit 0
  fi

  # Create temporary file
  TEMP_FILE=$(mktemp)
  trap cleanup EXIT

  # Get current month and day
  month_name=$(date +%B)
  day_of_month=$(date +%-d)

  # Create the curl command and CSS selector
  cat <<EOF >"${TEMP_FILE}"
curl "${BBC_URL}/${month_name,,}/${day_of_month}/default.stm"
a[href^="/onthisday/low/dates/stories"]
  span
EOF

  # Fetch and process the historical events
  if ! command -v pipet >/dev/null 2>&1; then
    echo "Error: 'pipet' command not found. Please install it and try again." >&2
    exit 1
  fi

  if ! command -v jq >/dev/null 2>&1; then
    echo "Error: 'jq' command not found. Please install it and try again." >&2
    exit 1
  fi

  if ! events=$(command pipet --json "${TEMP_FILE}" | command jq -r '.[0][0] | map(select(length > 0)) | .[]'); then
    echo "Error: Failed to fetch or process historical events." >&2
    exit 1
  fi

  if [[ -z "${events}" ]]; then
    echo "No historical events found for ${month_name} ${day_of_month}." >&2
    exit 0
  fi

  echo "Historical events for ${month_name} ${day_of_month}:"
  echo
  echo "${events}"
}

# Run the main function
main "$@"
