#!/usr/bin/env bash
set -euo pipefail

# Requires:
#   rustup component add llvm-tools-preview
#   cargo install cargo-llvm-cov --locked

run_out="$(mktemp)"
text_out="$(mktemp)"
html_out="$(mktemp)"

cleanup() {
  rm -f "$run_out" "$text_out" "$html_out"
}
trap cleanup EXIT

IGNORE_REGEX='src/bin/replay_bundle_capture\.rs|src/bin/replay_bundle_capture_delta\.rs|src/bin/replay_bundle_capture_sequence\.rs|src/bin/replay_bundle_record\.rs|src/bin/replay_bundle_refresh_sequence_outputs\.rs|src/bin/measure_sequence_replay\.rs|src/bin/repository_view_stats\.rs|src/bin/trace_arin_missing_vrps\.rs|src/bin/db_stats\.rs|src/bin/rrdp_state_dump\.rs|src/bin/ccr_dump\.rs|src/bin/ccr_verify\.rs|src/bin/ccr_to_routinator_csv\.rs|src/bin/ccr_to_compare_views\.rs|src/bin/cir_materialize\.rs|src/bin/cir_extract_inputs\.rs|src/bundle/live_capture\.rs|src/bundle/record_io\.rs|src/progress_log\.rs'

# Preserve colored output even though we post-process output by running under a pseudo-TTY.
# We run tests only once, then generate both CLI text + HTML reports without rerunning tests.
set +e

cargo llvm-cov clean --workspace >/dev/null 2>&1

# 1) Run tests once to collect coverage data (no report).
script -q -e -c "CARGO_TERM_COLOR=always cargo llvm-cov --no-report" "$run_out" >/dev/null 2>&1
run_status="$?"

# 2) CLI summary report + fail-under gate (no test rerun).
script -q -e -c "CARGO_TERM_COLOR=always cargo llvm-cov report --fail-under-lines 90 --ignore-filename-regex '$IGNORE_REGEX'" "$text_out" >/dev/null 2>&1
text_status="$?"

# 3) HTML report (no test rerun).
script -q -e -c "CARGO_TERM_COLOR=always cargo llvm-cov report --html --ignore-filename-regex '$IGNORE_REGEX'" "$html_out" >/dev/null 2>&1
html_status="$?"

set -e

strip_script_noise() {
  tr -d '\r' | sed '/^Script \(started\|done\) on /d'
}

strip_ansi_for_parse() {
  awk '
    {
      line = $0
      gsub(/\033\[[0-9;]*[A-Za-z]/, "", line) # CSI escapes
      gsub(/\033\([A-Za-z]/, "", line)        # charset escapes (e.g., ESC(B)
      gsub(/\r/, "", line)
      print line
    }
  '
}

cat "$run_out" | strip_script_noise
cat "$text_out" | strip_script_noise
cat "$html_out" | strip_script_noise

cat "$run_out" | strip_ansi_for_parse | awk '
  BEGIN {
    passed=0; failed=0; ignored=0; measured=0; filtered=0;
  }
  /^test result: / {
    if (match($0, /([0-9]+) passed; ([0-9]+) failed; ([0-9]+) ignored; ([0-9]+) measured; ([0-9]+) filtered out;/, m)) {
      passed += m[1]; failed += m[2]; ignored += m[3]; measured += m[4]; filtered += m[5];
    }
  }
  END {
    executed = passed + failed;
    total = passed + failed + ignored + measured;
    printf("\nTEST SUMMARY (all suites): passed=%d failed=%d ignored=%d measured=%d filtered_out=%d executed=%d total=%d\n",
           passed, failed, ignored, measured, filtered, executed, total);
  }
'

echo
echo "HTML report: target/llvm-cov/html/index.html"

status="$text_status"
if [ "$run_status" -ne 0 ]; then status="$run_status"; fi
if [ "$html_status" -ne 0 ]; then status="$html_status"; fi
exit "$status"
