#!/bin/bash
# Post-edit audit hook: Defense-in-Depth for High-Risk File Edits
#
# This hook runs AFTER every Edit/Write operation completes.
# It cannot prevent the edit (it already happened) but creates an
# audit trail that detects PreToolUse gate bypasses.
#
# If a high-risk file was edited but no session auth file exists,
# this logs a CONTROL_BYPASS event. This catches scenarios where:
# - The PreToolUse hook was disabled (disableAllHooks)
# - The PreToolUse hook had a logic error (YOLO-only bypass)
# - The PreToolUse hook was silently failing
#
# Receives JSON on stdin with tool_input.file_path.
# Always exits 0 (never blocks — the edit already happened).

set -euo pipefail

AUDIT_DIR="$HOME/.orxaq/audit"
AUDIT_LOG="$AUDIT_DIR/post_edit_audit.jsonl"

mkdir -p "$AUDIT_DIR"

INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

if [ -z "$FILE_PATH" ]; then
    exit 0
fi

# Check if this was a high-risk file
HIGH_RISK=false

case "$FILE_PATH" in
    */governance/*)     HIGH_RISK=true ;;
    */security/*)       HIGH_RISK=true ;;
    */auth*.py)         HIGH_RISK=true ;;
    */credential*.py)   HIGH_RISK=true ;;
    */.env*)            HIGH_RISK=true ;;
    *.pem)              HIGH_RISK=true ;;
    *.key)              HIGH_RISK=true ;;
    */hooks/*)          HIGH_RISK=true ;;
    *CLAUDE.md)         HIGH_RISK=true ;;
    *AGENTS.md)         HIGH_RISK=true ;;
    *fingerprint*.py)   HIGH_RISK=true ;;
    *biometric*.py)     HIGH_RISK=true ;;
    *execution_gate*.py) HIGH_RISK=true ;;
    */.github/workflows/*) HIGH_RISK=true ;;
esac

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

if [ "$HIGH_RISK" = "false" ]; then
    # Non-high-risk edit — log normally
    printf '{"timestamp":"%s","file_path":"%s","high_risk":false,"status":"normal"}\n' \
        "$TS" "$FILE_PATH" \
        >> "$AUDIT_LOG" 2>/dev/null || true
    exit 0
fi

# High-risk file was edited — check if PreToolUse gate was active
SESSION_AUTH_FILE="$HOME/.orxaq/audit/yolo_sessions/active"
PRE_HOOK_LOG="$AUDIT_DIR/hook_invocations.jsonl"

# Check if there's a recent PreToolUse invocation for this file (within last 10s)
PRE_HOOK_FIRED=false
if [ -f "$PRE_HOOK_LOG" ]; then
    # Check last 20 lines for a recent entry matching this file
    RECENT=$(tail -20 "$PRE_HOOK_LOG" 2>/dev/null | grep -c "$FILE_PATH" || true)
    if [ "$RECENT" -gt 0 ]; then
        PRE_HOOK_FIRED=true
    fi
fi

if [ "$PRE_HOOK_FIRED" = "true" ]; then
    # PreToolUse hook fired — normal flow
    printf '{"timestamp":"%s","file_path":"%s","high_risk":true,"status":"gate_active","session_auth":%s}\n' \
        "$TS" "$FILE_PATH" "$([ -f "$SESSION_AUTH_FILE" ] && echo 'true' || echo 'false')" \
        >> "$AUDIT_LOG" 2>/dev/null || true
else
    # PreToolUse hook did NOT fire — CONTROL BYPASS detected
    printf '{"timestamp":"%s","file_path":"%s","high_risk":true,"status":"CONTROL_BYPASS","session_auth":%s,"alert":"PreToolUse hook did not fire for high-risk edit"}\n' \
        "$TS" "$FILE_PATH" "$([ -f "$SESSION_AUTH_FILE" ] && echo 'true' || echo 'false')" \
        >> "$AUDIT_LOG" 2>/dev/null || true

    # Also write to a dedicated bypass alert file for easy detection
    BYPASS_LOG="$AUDIT_DIR/control_bypass_alerts.jsonl"
    printf '{"timestamp":"%s","file_path":"%s","alert":"CONTROL_BYPASS","detail":"High-risk file edited without PreToolUse biometric gate firing"}\n' \
        "$TS" "$FILE_PATH" \
        >> "$BYPASS_LOG" 2>/dev/null || true
fi

# Always exit 0 — this is a post-hook, cannot block
exit 0
