#!/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.

# Integration test for issue #121: an interrupted orchestrator writes an
# interrupted final status snapshot and does not leave a live updater behind.

set -uo pipefail

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

echo "=== status.json interrupted state and updater cleanup ==="
status_require_jq

PROJECT="$STATUS_TEST_TMPDIR/project"
FAKE_BIN="$STATUS_TEST_TMPDIR/bin"
OUT_FILE="$STATUS_TEST_TMPDIR/run.log"
mkdir -p "$FAKE_BIN"
status_setup_project "$PROJECT"

cat > "$FAKE_BIN/codex" <<'SH'
#!/usr/bin/env bash
trap 'exit 143' TERM INT
sleep 20
echo "Analysis complete. No findings."
echo "DONE"
exit 0
SH
chmod +x "$FAKE_BIN/codex"

setsid env \
  PATH="$FAKE_BIN:$PATH" \
  REPOLENS_STATUS_INTERVAL=1 \
  REPOLENS_LENS_HEARTBEAT_INTERVAL=1 \
  REPOLENS_AGENT_TIMEOUT=30 \
  bash "$STATUS_TEST_ROOT/repolens.sh" \
    --project "$PROJECT" \
    --agent codex \
    --focus i18n-strings \
    --change "status interrupt test" \
    --local \
    --yes \
    --parallel \
    --max-parallel 1 \
    >"$OUT_FILE" 2>&1 &
RUN_PID=$!

if RUN_ID="$(wait_for_run_id "$OUT_FILE")"; then
  status_register_run_id "$RUN_ID"
  TOTAL=$((TOTAL + 1))
  record_pass "Run id is logged"
else
  TOTAL=$((TOTAL + 1))
  record_fail "Run id is logged" "startup log did not contain run id"
fi

STATUS_FILE="$STATUS_TEST_ROOT/logs/$RUN_ID/status.json"
TOTAL=$((TOTAL + 1))
if [[ -n "$RUN_ID" ]] && wait_for_jq "$STATUS_FILE" '.state == "running" and .counts.active == 1' 60; then
  record_pass "Running status is visible before interrupt"
else
  record_fail "Running status is visible before interrupt" "missing $STATUS_FILE"
fi

if [[ -n "${RUN_PID:-}" ]] && kill -0 "$RUN_PID" 2>/dev/null; then
  kill -TERM "-$RUN_PID" 2>/dev/null || kill -TERM "$RUN_PID" 2>/dev/null || true
fi
wait_with_watchdog "$RUN_PID" 5
run_rc=$?
RUN_PID=""

TOTAL=$((TOTAL + 1))
if [[ "$run_rc" != "0" ]]; then
  record_pass "Interrupted RepoLens run exits non-zero"
else
  record_fail "Interrupted RepoLens run exits non-zero" "run exited cleanly after TERM"
fi

assert_jq "Interrupted status file is valid JSON" "$STATUS_FILE" '.'
assert_jq "Interrupted status records interrupted state" "$STATUS_FILE" '.state == "interrupted"'
assert_jq "Interrupted status exercised the parallel signal path" "$STATUS_FILE" '.parallel == true and .max_parallel == 1'

first_final_updated_at="$(jq -r '.updated_at // empty' "$STATUS_FILE" 2>/dev/null || true)"
sleep 1.4
second_final_updated_at="$(jq -r '.updated_at // empty' "$STATUS_FILE" 2>/dev/null || true)"
TOTAL=$((TOTAL + 1))
if [[ -n "$first_final_updated_at" && "$first_final_updated_at" == "$second_final_updated_at" ]] \
  && jq -e '.state == "interrupted"' "$STATUS_FILE" >/dev/null 2>&1; then
  record_pass "Final interrupted status is not overwritten by a live updater"
else
  record_fail "Final interrupted status is not overwritten by a live updater" \
    "first='${first_final_updated_at:-<empty>}' second='${second_final_updated_at:-<empty>}'"
fi

TOTAL=$((TOTAL + 1))
if command -v pgrep >/dev/null 2>&1; then
  updater_matches="$(pgrep -af "repolens-status-updater:$RUN_ID" 2>/dev/null | grep -v 'pgrep -af' || true)"
  if [[ -f "$STATUS_FILE" && -z "$updater_matches" ]]; then
    record_pass "No status updater process remains for the run"
  else
    record_fail "No status updater process remains for the run" "${updater_matches:-status file missing}"
  fi
else
  record_fail "No status updater process remains for the run" "pgrep unavailable"
fi

status_finish
