#!/usr/bin/env bash
# Copyright 2025-2026 Bootstrap Academy
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -uo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
source "$SCRIPT_DIR/tests/status_test_lib.sh"
source "$SCRIPT_DIR/lib/logging.sh"
source "$SCRIPT_DIR/lib/status.sh"
trap status_cleanup EXIT

echo "=== stale heartbeat recovery transition ==="
status_require_jq

RUN_ID="stale-recovery"
LOG_BASE="$STATUS_TEST_TMPDIR/$RUN_ID"
HEARTBEAT_DIR="$LOG_BASE/.heartbeat"
HEARTBEAT_FILE="$HEARTBEAT_DIR/security__xss.json"
STATE_FILE="$HEARTBEAT_DIR/security__xss.state"
AGE_FILE="$HEARTBEAT_DIR/security__xss.state-age"
LOG_FILE="$LOG_BASE/$RUN_ID.log"
mkdir -p "$HEARTBEAT_DIR"
init_logging "$RUN_ID" "$LOG_BASE"

now_iso="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
jq -cn \
  --arg run_id "$RUN_ID" \
  --arg domain "security" \
  --arg lens_id "xss" \
  --arg now_iso "$now_iso" \
  '{
    run_id: $run_id,
    domain: $domain,
    lens_id: $lens_id,
    pid: 4242,
    iteration: 4,
    started_at: $now_iso,
    last_heartbeat_at: $now_iso,
    state: "running"
  }' > "$HEARTBEAT_FILE"
printf 'warn\n' > "$STATE_FILE"
printf '145\n' > "$AGE_FILE"

log_count() {
  local pattern="$1"
  grep -Ec "$pattern" "$LOG_FILE" 2>/dev/null || true
}

check_stale_heartbeats "$RUN_ID" "$LOG_BASE" "$HEARTBEAT_DIR" 120 600
assert_eq "Recovery transition logs exactly once" "1" "$(log_count '\[INFO\].*\[security/xss\] heartbeat recovered')"
assert_contains "Recovery reports prior silence duration" "heartbeat recovered after 145s of silence" "$(cat "$LOG_FILE")"
assert_eq "Recovery resets state to ok" "ok" "$(cat "$STATE_FILE")"

TOTAL=$((TOTAL + 1))
if [[ ! -e "$AGE_FILE" ]]; then
  record_pass "Recovery clears stale age sidecar"
else
  record_fail "Recovery clears stale age sidecar" "still present at $AGE_FILE"
fi

check_stale_heartbeats "$RUN_ID" "$LOG_BASE" "$HEARTBEAT_DIR" 120 600
assert_eq "Recovered heartbeat does not log repeatedly" "1" "$(log_count '\[INFO\].*\[security/xss\] heartbeat recovered')"

status_finish
