# gen_mk.awk — Turn benchmark configuration CSVs into a make fragment.
#
# Invoke as:
#   awk -v reps=3 -v build='bench/build' -v results='bench/results/latest' \
#       -f bench/gen_mk.awk bench/types.csv bench/nonrec.csv ...
#
# `reps` is the number of repetitions per benchmark; the resulting
# .out files use 0..reps-1 as their index suffix.
#
# For each row in <dim>.csv we emit:
#   - a .v target with a gen_bench.ml recipe,
#   - <reps> explicit dependency lines linking the matching .out files
#     back to the .v file, so the generic %.out pattern rule in
#     CoqMakefile.local can pick them up,
#   - a dependency line adding each .out to the per-dimension summary
#     CSV target.

BEGIN {
    if (reps == "")    reps    = 1
    if (build == "")   build   = "bench/build"
    if (results == "") results = "bench/results/latest"
    print "# Auto-generated by bench/gen_mk.awk — do not edit."
}

FNR == 1 {
    # Extract dimension name from the file path: strip dir and .csv.
    dim = FILENAME
    sub(/.*\//, "", dim)
    sub(/\.csv$/, "", dim)
    nfields = split($0, header, ",")
    next
}

{
    nrow = split($0, row, ",")
    if (nrow == 0 || row[1] == "") next

    value = row[1]
    # Prefix with "v" so the resulting filename is a valid Rocq module
    # name (they can't start with a digit).
    vfile = build "/" dim "/v" value ".v"

    # gen_bench.ml CLI: column names (after `value`) map to -<name>.
    cmd = "ocaml bench/gen_bench.ml"
    for (i = 2; i <= nfields; i++) {
        cmd = cmd " -" header[i] " " row[i]
    }
    cmd = cmd " -o $@"

    # .v recipe.
    printf "%s: bench/gen_bench.ml\n", vfile
    printf "\t$(SHOW)'GEN-BENCH %s'\n", vfile
    printf "\t$(HIDE)mkdir -p $(@D)\n"
    printf "\t$(HIDE)%s\n", cmd

    # Per-rep .out → .v dependency + summary rollup.
    outs = ""
    for (rep = 0; rep < reps; rep++) {
        out = build "/" dim "/v" value "-" rep ".out"
        outs = (outs == "" ? out : outs " " out)
    }
    printf "%s: %s\n", outs, vfile
    printf "%s/%s.csv: %s\n", results, dim, outs
}
