#!/usr/bin/env bash
# core/framework/hook.sh
#
# Simple callback registry — fire named hooks, register handlers.
#
# Usage:
#   hook::on  "command:help"  my_handler_function
#   hook::off "command:help"  my_handler_function
#   hook::fire "command:help" arg1 arg2
#
# If no handler registered, hook::fire returns 0 silently.
# hook::fire returns the exit code of the handler.

# Registry: event_name → handler_function
declare -gA _HOOK_REGISTRY=()

# hook::on <event> <handler>
# Register a handler for an event. Replaces existing handler.
function hook::on() {
  local event="${1:-}" handler="${2:-}"
  [[ -z "$event" || -z "$handler" ]] && return 1
  _HOOK_REGISTRY["$event"]="$handler"
}

# hook::off <event>
# Remove handler for an event.
function hook::off() {
  local event="${1:-}"
  [[ -z "$event" ]] && return 1
  unset "_HOOK_REGISTRY[$event]"
}

# hook::fire <event> [args...]
# Call registered handler with args. Silent no-op if no handler.
function hook::fire() {
  local event="${1:-}"
  shift || true
  local handler="${_HOOK_REGISTRY[$event]:-}"
  [[ -z "$handler" ]] && return 0
  "$handler" "$@"
}

# hook::has <event>
# Returns 0 if a handler is registered for event.
function hook::has() {
  [[ -n "${_HOOK_REGISTRY[$1]:-}" ]]
}