#!/usr/bin/env bash
# Recompute the shake-vs-VND time breakdown from the saved *.folded files.
# Weights are perf sample periods (proportional to on-CPU time), so the
# percentages are time fractions. No re-profiling needed.
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${HERE}/cases.sh"

# Emit a per-case breakdown for one folded file. $1=folded, $2=title, $3=nsamples
breakdown() {
  awk -v TITLE="$2" -v NS="$3" '
    { c=$NF; total+=c
      if      ($0 ~ /shake3/)                       sh+=c
      else if ($0 ~ /vnd1/)                          v1+=c
      else if ($0 ~ /vnd2bi/)                        v2+=c
      else if ($0 ~ /vnd3bi/)                        v3+=c
      else if ($0 ~ /prim_original/)                 pr+=c
      else if ($0 ~ /operator=|_Hashtable/)          cp+=c   # Solution copy in main
      else                                           ot+=c
    }
    function p(x){ return total>0 ? 100.0*x/total : 0 }
    END{
      printf "case:          %s\n", TITLE
      printf "perf samples:  %s   (weights = sample periods, proportional to CPU time)\n\n", NS
      printf "%-16s %9s\n", "region", "cpu %"
      printf "%-16s %8.2f%%\n", "shake3 (SHAKE)", p(sh)
      printf "%-16s %8.2f%%\n", "vnd1",           p(v1)
      printf "%-16s %8.2f%%\n", "vnd2bi",         p(v2)
      printf "%-16s %8.2f%%\n", "vnd3bi",         p(v3)
      printf "%-16s %8.2f%%\n", "sol-copy(main)", p(cp)
      printf "%-16s %8.2f%%\n", "prim (init)",    p(pr)
      printf "%-16s %8.2f%%\n", "other",          p(ot)
      printf "  %s\n", "----------------------------"
      printf "%-16s %8.2f%%\n", "VND total",   p(v1+v2+v3)
      printf "%-16s %8.2f%%\n", "SHAKE total", p(sh)
    }' "$1"
}

COMBINED="${OUT}/summary_combined.txt"
: > "${COMBINED}"
for entry in "${CASES[@]}"; do
  IFS='|' read -r name d k file kmax iters seed bk <<< "${entry}"
  folded="${OUT}/${name}.folded"
  [[ -s "${folded}" ]] || { echo "skip ${name}: no ${folded}"; continue; }
  # sample count (cosmetic); tolerate SIGPIPE/failures without aborting the script
  set +e +o pipefail
  ns="$(perf report --stdio -i "${OUT}/${name}.data" 2>/dev/null | grep -m1 '# Samples:' | sed -E 's/.*# Samples: *([0-9]+[KMG]?).*/\1/')"
  set -e -o pipefail
  [[ -n "${ns:-}" ]] || ns="?"
  title="${name}: ${file##*/} d=${d} k=${k} seed=${seed}"
  out="$(breakdown "${folded}" "${title}" "${ns}")"
  echo "${out}" | tee "${OUT}/${name}.summary.txt"
  echo
  { echo "${out}"; echo; echo "=================================================="; echo; } >> "${COMBINED}"
done
echo "Combined breakdown: ${COMBINED}"
