#!/usr/bin/env bash
# AY Framework -- HANDOFF schema validation gate.
# Rejects malformed HANDOFF entries before they are written to
# .ay/tracking/HANDOFFS.md. Called by /task-done and /go (Phase 10, LEARN).
#
# Usage:
#   ayf-handoff-validate <file>     # validate the HANDOFF block in <file>
#   ayf-handoff-validate -          # read the HANDOFF block from stdin
#   printf '%s' "$entry" | ayf-handoff-validate
#
# Exit codes: 0 = valid, 1 = invalid (per-field errors on stderr),
#             64 = usage error.
#
# Canonical schema -- required labeled fields, one per line:
#   To:      <agent-name | all>
#   From:    <agent-name>
#   Subject: <one-line summary>
#   Date:    <YYYY-MM-DD HH:MM>
#   Detail:  <free-form body>            # optional
#
# Pure bash + grep/sed, no external deps -- matches the other hooks/scripts in
# this repo. Works on Mac, Linux, Windows (Git Bash).

set -euo pipefail

REQUIRED_FIELDS="To From Subject Date"

usage() {
  echo "usage: ayf-handoff-validate <file|->  (or pipe a HANDOFF entry on stdin)" >&2
  exit 64
}

# --- Read the entry -------------------------------------------------------
if [ "$#" -gt 1 ]; then
  usage
fi

if [ "$#" -eq 1 ] && [ "$1" != "-" ]; then
  if [ ! -f "$1" ]; then
    echo "ayf-handoff-validate: file not found: $1" >&2
    exit 1
  fi
  ENTRY="$(cat "$1")"
else
  # stdin: explicit "-" or no arg
  ENTRY="$(cat)"
fi

if [ -z "${ENTRY//[[:space:]]/}" ]; then
  echo "ayf-handoff-validate: empty HANDOFF entry" >&2
  exit 1
fi

# --- Helpers --------------------------------------------------------------
has_field() {
  local field="$1"
  printf '%s\n' "$ENTRY" | grep -qE "^[[:space:]]*${field}:"
}

field_value() {
  # Print the trimmed value of the first "Field:" line, or nothing.
  local field="$1"
  printf '%s\n' "$ENTRY" \
    | grep -m1 -E "^[[:space:]]*${field}:" \
    | sed -E "s/^[[:space:]]*${field}:[[:space:]]*//" \
    | sed -E 's/[[:space:]]+$//'
}

# --- Validate required fields (present AND non-empty) ---------------------
ERRORS=""
for field in $REQUIRED_FIELDS; do
  if ! has_field "$field"; then
    ERRORS="${ERRORS}  - missing required field: ${field}:\n"
    continue
  fi
  if [ -z "$(field_value "$field")" ]; then
    ERRORS="${ERRORS}  - field '${field}:' is present but has no value\n"
  fi
done

# --- Validate Date shape (YYYY-MM-DD HH:MM) when present with a value -----
if has_field "Date"; then
  date_value="$(field_value "Date")"
  if [ -n "$date_value" ] \
     && ! printf '%s' "$date_value" | grep -qE '^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$'; then
    ERRORS="${ERRORS}  - field 'Date:' must match YYYY-MM-DD HH:MM (got: ${date_value})\n"
  fi
fi

# --- Report ---------------------------------------------------------------
if [ -n "$ERRORS" ]; then
  echo "ayf-handoff-validate: HANDOFF entry rejected -- schema violations:" >&2
  printf '%b' "$ERRORS" >&2
  echo "  Required schema: To, From, Subject, Date (YYYY-MM-DD HH:MM)." >&2
  exit 1
fi

exit 0
