```bash
#!/usr/bin/env bash
#
# checksum_guard.sh
#
# A production-quality utility for recording, verifying, and diffing
# SHA-256 checksums of files within a directory tree.
#
# Subcommands:
#   record <dir> <manifest>   Compute checksums and save to manifest.
#   verify <dir> <manifest>   Compare current state against manifest.
#   diff   <dir> <manifest>   Human-readable summary of discrepancies.
#
# Exit codes:
#   0  Success (no discrepancies for verify/diff)
#   1  Discrepancies found (verify/diff)
#   2  Usage error or invalid arguments
#   3  Runtime error (e.g., missing directory, unreadable manifest)
#
# Dependencies:
#   - bash >= 4.0 (for associative arrays)
#   - sha256sum (coreutils)
#   - find, sort, awk, sed, grep, cut, wc, printf, date
#
# Author: Generated for agent_broker endpoint smoke test
# Date: 2024

set -euo pipefail

# =============================================================================
# Configuration & Constants
# =============================================================================

readonly SCRIPT_NAME="$(basename "$0")"
readonly MANIFEST_VERSION="1.0"
readonly TIMESTAMP_FORMAT="%Y-%m-%dT%H:%M:%S%z"

# Colors for output (disabled if not a TTY)
if [[ -t 1 ]]; then
    readonly COLOR_RED=$'\033[0;31m'
    readonly COLOR_GREEN=$'\033[0;32m'
    readonly COLOR_YELLOW=$'\033[0;33m'
    readonly COLOR_BLUE=$'\033[0;34m'
    readonly COLOR_RESET=$'\033[0m'
else
    readonly COLOR_RED=""
    readonly COLOR_GREEN=""
    readonly COLOR_YELLOW=""
    readonly COLOR_BLUE=""
    readonly COLOR_RESET=""
fi

# =============================================================================
# Utility Functions
# =============================================================================

# Print usage information
usage() {
    cat <<EOF
Usage: ${SCRIPT_NAME} <subcommand> [options]

Subcommands:
  record <dir> <manifest>
      Compute SHA-256 checksums of all files under <dir> and save them
      to <manifest> with a version header and timestamp.

  verify <dir> <manifest>
      Recompute checksums and compare against <manifest>.
      Reports ADDED, MODIFIED, and DELETED files.
      Exits with code 1 if any discrepancies are found.

  diff <dir> <manifest>
      Human-readable summary table with counts of ADDED, MODIFIED,
      and DELETED files. Exits with code 1 if any discrepancies exist.

Options:
  -h, --help      Show this help message and exit.

Examples:
  ${SCRIPT_NAME} record ./src ./checksums.manifest
  ${SCRIPT_NAME} verify ./src ./checksums.manifest
  ${SCRIPT_NAME} diff ./src ./checksums.manifest

EOF
}

# Print error message to stderr
error() {
    echo "${COLOR_RED}ERROR:${COLOR_RESET} $*" >&2
}

# Print warning message to stderr
warn() {
    echo "${COLOR_YELLOW}WARNING:${COLOR_RESET} $*" >&2
}

# Print info message to stderr
info() {
    echo "${COLOR_BLUE}INFO:${COLOR_RESET} $*" >&2
}

# Check if a command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Validate that a directory exists and is readable
validate_dir() {
    local dir="$1"
    if [[ ! -d "$dir" ]]; then
        error "Directory does not exist or is not a directory: $dir"
        return 1
    fi
    if [[ ! -r "$dir" ]]; then
        error "Directory is not readable: $dir"
        return 1
    fi
    return 0
}

# Validate that a manifest file exists and is readable
validate_manifest() {
    local manifest="$1"
    if [[ ! -f "$manifest" ]]; then
        error "Manifest file does not exist: $manifest"
        return 1
    fi
    if [[ ! -r "$manifest" ]]; then
        error "Manifest file is not readable: $manifest"
        return 1
    fi
    return 0
}

# =============================================================================
# Core Logic: Checksum Computation
# =============================================================================

# Compute SHA-256 checksums for all files under a directory.
# Outputs lines in the format: <checksum>  <relative_path>
# Uses find -print0 and null-delimited iteration to handle any filename.
#
# Arguments:
#   $1 - Directory to scan
#
# Output:
#   Lines of "<sha256>  <relative_path>" sorted by path
compute_checksums() {
    local dir="$1"
    local tmpfile
    tmpfile="$(mktemp)"
    trap "rm -f '$tmpfile'" RETURN

    # Use find with -print0 to handle filenames with spaces, newlines, etc.
    # We process each file individually to compute its checksum.
    # The relative path is computed by stripping the leading directory prefix.
    #
    # Note: We use a subshell to avoid polluting the main shell's variables.
    (
        cd "$dir" || exit 1
        find . -type f -print0 | while IFS= read -r -d '' file; do
            # Compute checksum. sha256sum outputs "<hash>  <filename>"
            # We extract just the hash and pair it with the relative path.
            local hash
            hash="$(sha256sum "$file" | awk '{print $1}')"
            # Output: hash followed by two spaces and the relative path
            printf '%s  %s\n' "$hash" "$file"
        done
    ) > "$tmpfile"

    # Sort by path (second field onwards) for deterministic output
    sort -k2 "$tmpfile"
}

# =============================================================================
# Core Logic: Manifest Parsing
# =============================================================================

# Parse a manifest file and output lines in the format: <checksum>  <relative_path>
# Skips comment lines (starting with #) and blank lines.
#
# Arguments:
#   $1 - Path to manifest file
#
# Output:
#   Lines of "<sha256>  <relative_path>"
parse_manifest() {
    local manifest="$1"
    # Skip lines starting with # and empty lines
    grep -v '^#' "$manifest" | grep -v '^[[:space:]]*$' || true
}

# =============================================================================
# Core Logic: Comparison
# =============================================================================

# Compare two sets of checksums (current vs recorded) and categorize differences.
#
# Arguments:
#   $1 - File containing current checksums (sorted)
#   $2 - File containing recorded checksums (sorted)
#
# Output:
#   Lines prefixed with ADDED:, MODIFIED:, or DELETED: followed by the path.
#   ADDED:   File exists in current but not in recorded.
#   MODIFIED: File exists in both but checksums differ.
#   DELETED:  File exists in recorded but not in current.
compare_checksums() {
    local current_file="$1"
    local recorded_file="$2"

    # Use awk to perform the comparison efficiently.
    # We load the recorded checksums into an associative array, then
    # iterate through current checksums to find matches/mismatches.
    # Finally, we check for recorded entries not seen in current.

    awk '
    BEGIN {
        # Read recorded checksums into an associative array
        while ((getline line < recorded_file) > 0) {
            # Skip empty lines
            if (line == "") continue
            # Split into hash and path. The format is "<hash>  <path>"
            # We use the first field as hash and the rest as path.
            split(line, parts, "  ")
            hash = parts[1]
            path = parts[2]
            # Handle paths with spaces: reconstruct path from remaining parts
            for (i = 3; i <= length(parts); i++) {
                path = path "  " parts[i]
            }
            recorded[path] = hash
        }
        close(recorded_file)

        # Process current checksums
        while ((getline line < current_file) > 0) {
            if (line == "") continue
            split(line, parts, "  ")
            hash = parts[1]
            path = parts[2]
            for (i = 3; i <= length(parts); i++) {
                path = path "  " parts[i]
            }

            if (path in recorded) {
                if (recorded[path] != hash) {
                    print "MODIFIED:" path
                }
                # Mark as seen by deleting from recorded
                delete recorded[path]
            } else {
                print "ADDED:" path
            }
        }
        close(current_file)

        # Any remaining entries in recorded are DELETED
        for (path in recorded) {
            print "DELETED:" path
        }
    }
    ' recorded_file="$recorded_file" current_file="$current_file"
}

# =============================================================================
# Subcommand: record
# =============================================================================

cmd_record() {
    local dir="$1"
    local manifest="$2"

    # Validate inputs
    if ! validate_dir "$dir"; then
        return 3
    fi

    # Ensure manifest directory exists
    local manifest_dir
    manifest_dir="$(dirname "$manifest")"
