#!/bin/bash
# log-event.sh — append a structured event to HQ-Vault/_System/AgentLog/events.ndjson
#
# Usage:
#   log-event.sh <agent> <action> <target> <result> [<notes>]
#
# Schema (one JSON object per line):
#   ts:     ISO8601 UTC timestamp
#   agent:  agent identity (claude-code-opsman, hermes, cron:vault-health, etc.)
#   action: commit | push | skill_run | cron_run | file_write | file_archive | ...
#   target: file path, skill name, or other reference
#   result: ok | fail | warn
#   notes:  free-text (optional)
#
# Example:
#   log-event.sh "cron:vault-health" "cron_run" "HealthLog.md" "ok" "daily probe complete"
#
# Designed to be idempotent and safe to call from any script. Failure to log
# does NOT propagate — calling script continues normally.

set -u

AGENT="${1:-unknown}"
ACTION="${2:-unknown}"
TARGET="${3:-}"
RESULT="${4:-ok}"
NOTES="${5:-}"

# Locate vault root by walking up from script location
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VAULT_ROOT="${SCRIPT_DIR}/../HQ-Vault"
EVENTS_FILE="${VAULT_ROOT}/_System/AgentLog/events.ndjson"

if [ ! -d "$(dirname "$EVENTS_FILE")" ]; then
    # AgentLog dir doesn't exist yet — silently exit 0 (don't break callers)
    exit 0
fi

TS=$(date -u +%Y-%m-%dT%H:%M:%SZ)

# JSON-escape strings (basic — handles backslash and double-quote)
escape_json() {
    printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'
}

AGENT_E=$(escape_json "$AGENT")
ACTION_E=$(escape_json "$ACTION")
TARGET_E=$(escape_json "$TARGET")
RESULT_E=$(escape_json "$RESULT")
NOTES_E=$(escape_json "$NOTES")

# Append one line; flock to avoid concurrent writes corrupting the file.
# On Windows (Git Bash / MSYS2) flock is not bundled — degrade to lock-free
# write so the helper still works for single-agent local sessions.
{
    if command -v flock >/dev/null 2>&1; then
        flock -x 200
    fi
    printf '{"ts":"%s","agent":"%s","action":"%s","target":"%s","result":"%s","notes":"%s"}\n' \
        "$TS" "$AGENT_E" "$ACTION_E" "$TARGET_E" "$RESULT_E" "$NOTES_E" \
        >> "$EVENTS_FILE"
} 200>"${EVENTS_FILE}.lock"

exit 0
