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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root"

report_path="${BENCHMARK_REPORT_PATH:-target/benchmark-local-report.md}"
sample_size="${BENCHMARK_SAMPLE_SIZE:-20}"
measurement_time="${BENCHMARK_MEASUREMENT_TIME:-5}"
bench_targets_raw="${BENCHMARK_REPORT_BENCHES:-cdc_perf quality_perf}"
run_enabled="${BENCHMARK_RUN_ENABLED:-1}"
strict_mode="${BENCHMARK_STRICT:-0}"
regression_threshold="${BENCHMARK_MAX_REGRESSION_PERCENT:-999}"
allow_non_release_root_report="${BENCHMARK_ALLOW_NON_RELEASE_REPORT:-0}"
baseline_commit="${BENCHMARK_BASELINE_COMMIT:-}"
baseline_artifact="${BENCHMARK_BASELINE_ARTIFACT:-}"

contains_bench_target() {
  local wanted="$1"
  shift
  local bench
  for bench in "$@"; do
    if [[ "$bench" == "$wanted" ]]; then
      return 0
    fi
  done
  return 1
}

report_classification="non-release-local"
report_classification_reason="generated by ad-hoc report script"

IFS=' ' read -r -a bench_targets <<< "$bench_targets_raw"
if [[ "${#bench_targets[@]}" -eq 0 ]]; then
  echo "No benchmark targets configured (BENCHMARK_REPORT_BENCHES)."
  exit 1
fi

current_commit="$(git rev-parse HEAD 2>/dev/null || true)"
git_tree_state="unknown"
if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  if git diff --quiet --ignore-submodules HEAD --; then
    git_tree_state="clean"
  else
    git_tree_state="dirty"
  fi
fi

if [[ "$strict_mode" == "1" ]] \
  && awk -v val="$regression_threshold" 'BEGIN { exit (val + 0 <= 5 ? 0 : 1) }' \
  && contains_bench_target "quality_perf" "${bench_targets[@]}" \
  && contains_bench_target "cdc_perf" "${bench_targets[@]}" \
  && [[ -n "$baseline_commit" ]] \
  && [[ "$baseline_commit" == "$current_commit" ]] \
  && [[ -n "$baseline_artifact" ]] \
  && [[ "$git_tree_state" == "clean" ]]; then
  report_classification="release-gate-eligible"
  report_classification_reason="strict policy, commit-pinned baseline, and clean tree"
fi

if [[ "$report_path" == "BENCHMARK_REPORT.md" ]] \
  && [[ "$report_classification" != "release-gate-eligible" ]] \
  && [[ "$allow_non_release_root_report" != "1" ]]; then
  cat >&2 <<EOF
Refusing to write non-release benchmark evidence to BENCHMARK_REPORT.md.
classification=${report_classification}
reason=${report_classification_reason}

Use one of the following:
  1) Keep default output at target/benchmark-local-report.md for local runs.
  2) Set BENCHMARK_ALLOW_NON_RELEASE_REPORT=1 to override intentionally.
  3) Run with strict release-gate settings (BENCHMARK_STRICT=1, threshold <= 5, and both quality_perf + cdc_perf).
EOF
  exit 1
fi

mkdir -p target

{
  echo "# Benchmark Report"
  echo
  if [[ "$report_classification" != "release-gate-eligible" ]]; then
    echo "> WARNING: This report is ${report_classification}. Do not treat it as release baseline evidence."
    echo "> Reason: ${report_classification_reason}."
    echo
  fi
  echo "Generated: $(date -u '+%Y-%m-%dT%H:%M:%SZ')"
  echo
  echo "## Environment"
  echo
  echo '```text'
  uname -a
  rustc -Vv
  echo "bench_targets=${bench_targets_raw}"
  echo "git_commit=${current_commit:-unknown}"
  echo "git_tree_state=${git_tree_state}"
  echo "baseline_commit=${baseline_commit}"
  echo "baseline_artifact=${baseline_artifact}"
  echo "regression_threshold_percent=${regression_threshold}"
  echo "strict_mode=${strict_mode}"
  echo "report_classification=${report_classification}"
  echo "report_classification_reason=${report_classification_reason}"
  echo '```'
  echo
  echo "## Benchmarks"
} > "$report_path"

for bench in "${bench_targets[@]}"; do
  raw_out="target/benchmark-${bench}.txt"

  {
    echo
    echo "### ${bench}"
    echo
    echo '```bash'
    echo "cargo bench --bench ${bench} -- --sample-size ${sample_size} --measurement-time ${measurement_time}"
    echo '```'
  } >> "$report_path"

  if [[ "$run_enabled" == "1" ]]; then
    cargo bench --bench "$bench" -- --sample-size "$sample_size" --measurement-time "$measurement_time" | tee "$raw_out"
  else
    printf "BENCHMARK_RUN_ENABLED=0, skipped execution for %s\n" "$bench" | tee "$raw_out"
  fi

  {
    echo
    echo "#### Raw Output"
    echo
    echo '```text'
    cat "$raw_out"
    echo '```'
  } >> "$report_path"

done

printf "Wrote %s\n" "$report_path"
