#!/bin/sh
#
# Pre-commit hook for knots
# Checks the complexity of every staged file knots can analyse
#
# Installation:
#   cp pre-commit .git/hooks/pre-commit
#   chmod +x .git/hooks/pre-commit
#

# Configuration (can be overridden via git config)
MCCABE_THRESHOLD=${MCCABE_THRESHOLD:-$(git config hooks.knots.mccabe-threshold || printf '%s\n' "15")}
COGNITIVE_THRESHOLD=${COGNITIVE_THRESHOLD:-$(git config hooks.knots.cognitive-threshold || printf '%s\n' "15")}
NESTING_THRESHOLD=${NESTING_THRESHOLD:-$(git config hooks.knots.nesting-threshold || printf '%s\n' "5")}
SLOC_THRESHOLD=${SLOC_THRESHOLD:-$(git config hooks.knots.sloc-threshold || printf '%s\n' "50")}
ABC_THRESHOLD=${ABC_THRESHOLD:-$(git config hooks.knots.abc-threshold || printf '%s\n' "10.0")}
RETURN_THRESHOLD=${RETURN_THRESHOLD:-$(git config hooks.knots.return-threshold || printf '%s\n' "3")}
VALIDATOR_PATH=${VALIDATOR_PATH:-$(git config hooks.knots.path || which knots)}
VERBOSE=${VERBOSE:-$(git config hooks.knots.verbose || printf '%s\n' "false")}

# Colors for output
RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

# knots --format ndjson prints one JSON record per function, ordered by name.
# Reading the records rather than the text report keeps a change of report
# layout from silently switching a threshold off.
#
# NUM_AWK reads a numeric field of the record on the current line.
NUM_AWK='
function num(key,    p, s) {
    p = index($0, "\"" key "\":")
    if (p == 0) return ""
    s = substr($0, p + length(key) + 3)
    if (!match(s, /^-?[0-9][0-9.eE+-]*/)) return ""
    return substr(s, 1, RLENGTH)
}
'

# BREACHES_AWK prints "LINE<TAB>SEQ<TAB>LABEL<TAB>MESSAGE" for each metric
# over its threshold, in the order the text report lists the metrics.
# breaches() sorts by LINE, to put functions in source order as the report
# does. LABEL is file:line:function, as the report names a function; a tab or
# newline in it stays escaped (\t, \n), so it cannot split the line. ABC is
# compared unrounded, as knots compares it, and shown to two decimal places,
# as the report shows it.
BREACHES_AWK="$NUM_AWK"'
function str(key,    p, s, c, out) {
    p = index($0, "\"" key "\":\"")
    if (p == 0) return ""
    s = substr($0, p + length(key) + 4)
    out = ""
    while (s != "") {
        c = substr(s, 1, 1)
        if (c == "\"") break
        if (c == "\\") {
            c = substr(s, 2, 1)
            s = substr(s, 3)
            if (c == "n" || c == "t" || c == "r") c = "\\" c
            else if (c == "u") { c = "?"; s = substr(s, 5) }
        } else {
            s = substr(s, 2)
        }
        out = out c
    }
    return out
}
function check(label, name, value, limit, shown) {
    if (value == "" || limit == "" || value + 0 <= limit + 0) return
    if (shown == "") shown = value
    printf "%s\t%d\t%s\t%s: %s (threshold: %s)\n", \
        line + 0, ++seq, label, name, shown, limit
}
/^\{/ {
    line = num("start_line")
    label = str("file") ":" line ":" str("function")
    check(label, "McCabe Complexity", num("mccabe"), mccabe)
    check(label, "Cognitive Complexity", num("cognitive"), cognitive)
    check(label, "Nesting Depth", num("nesting"), nesting)
    check(label, "SLOC", num("sloc"), sloc)
    abc = num("abc_magnitude")
    shown = abc == "" ? "" : sprintf("%.2f", abc)
    check(label, "ABC Magnitude", abc, abc_limit, shown)
    check(label, "Return Count", num("return_count"), returns)
}
'

# Print "LABEL<TAB>MESSAGE" for each breach in $1, knots --format ndjson
# output, in source order.
breaches() {
    printf '%s\n' "$1" | awk -v mccabe="$MCCABE_THRESHOLD" \
        -v cognitive="$COGNITIVE_THRESHOLD" -v nesting="$NESTING_THRESHOLD" \
        -v sloc="$SLOC_THRESHOLD" -v abc_limit="$ABC_THRESHOLD" \
        -v returns="$RETURN_THRESHOLD" "$BREACHES_AWK" |
        sort -t "$TAB" -k1,1n -k2,2n | cut -f3-
}

# SUMMARY_AWK prints the first lines of the text report's Summary, from the
# same records, so --verbose needs no second knots run.
SUMMARY_AWK="$NUM_AWK"'
/^\{/ {
    n++
    mc += num("mccabe"); cg += num("cognitive")
    ne += num("nesting"); sl += num("sloc")
}
END {
    print "Summary:"
    printf "  Total Functions: %d\n", n
    printf "  Total McCabe Complexity: %d\n", mc
    printf "  Total Cognitive Complexity: %d\n", cg
    printf "  Total Nesting Depth: %d\n", ne
    printf "  Total SLOC: %d\n", sl
}
'

# Print the Summary for $1, knots --format ndjson output.
summary() {
    printf '%s\n' "$1" | awk "$SUMMARY_AWK"
}

TAB=$(printf '\t')

# The extensions knots analyses (`knots --supported-languages`, explicit-only
# .h and .ads included), matched in any letter case as knots matches them.
# tests/hook_scripts.rs keeps this list equal to knots' language registry.
SOURCE_EXT='\.(c|h|cpp|cc|cxx|hpp|hxx|rs|py|js|mjs|cjs|jsx|ts|tsx|adb|ada|ads|go|java|cs|kt|kts|swift|php|f90|f95|f03|f08|scala|sc|lua)$'

# Get list of supported source files being committed
# One path per line; core.quotePath=false keeps non-ASCII names as they are
# rather than quoted, so they match on disk.
C_FILES=$(git -c core.quotePath=false diff --cached --name-only --diff-filter=ACM |
    grep -iE "$SOURCE_EXT")

if [ -z "$C_FILES" ]; then
    # No supported source files in this commit
    exit 0
fi

# Source files are staged, so a missing knots fails the commit rather than
# letting it through unchecked.
if [ ! -x "$VALIDATOR_PATH" ]; then
    printf '%b\n' "${RED}Error: knots not found${VALIDATOR_PATH:+ at $VALIDATOR_PATH}${NC}" >&2
    printf '%s\n' "Install it or set the path with: git config hooks.knots.path /path/to/knots" >&2
    printf '%s\n' "To commit without the check (not recommended): git commit --no-verify" >&2
    exit 1
fi

# Run knots on $1 and leave its ndjson records in OUTPUT and its exit status
# in STATUS. Anything knots writes to stderr (a file it could not read, one
# with syntax errors and no function recovered) is printed, not dropped, so
# a file knots could not analyse never looks like a clean one. knots exits 3
# when it could not analyse the file and 1 when its own check failed (a
# threshold set in knots.toml, or an error such as an unreadable knots.toml).
ERR_FILE=$(mktemp) || exit 2
trap 'rm -f "$ERR_FILE"' EXIT
run_knots() {
    OUTPUT=$("$VALIDATOR_PATH" --format ndjson "$1" 2>"$ERR_FILE" </dev/null)
    STATUS=$?
    if [ -s "$ERR_FILE" ]; then
        sed 's/^/  knots: /' "$ERR_FILE"
    fi
}

printf '%s\n' "Running knots on staged files..."
printf '%s\n' ""

FAILED=0
NOT_ANALYSED=0
KNOTS_FAILED=0

while IFS= read -r file; do
    if [ ! -f "$file" ]; then
        continue
    fi

    run_knots "$file"
    case $STATUS in
        0) ;;
        1)
            printf '%b%s%b\n' "$RED" "✗ $file: knots' own check failed (exit 1); see the knots: lines above" "$NC"
            KNOTS_FAILED=1
            ;;
        *)
            printf '%b%s%b\n' "$RED" "✗ $file: not analysed (knots exited $STATUS)" "$NC"
            NOT_ANALYSED=1
            continue
            ;;
    esac

    while IFS="$TAB" read -r label message; do
        [ -n "$label" ] || continue
        printf '%b%s%b\n' "$RED" "✗ $label" "$NC"
        printf '%s\n' "  $message"
        FAILED=1
    done <<EOF
$(breaches "$OUTPUT")
EOF

    # Show summary if verbose
    if [ "$VERBOSE" = "true" ]; then
        summary "$OUTPUT"
        printf '%s\n' ""
    fi
done <<FILES
$C_FILES
FILES

if [ $NOT_ANALYSED -eq 0 ] && [ $KNOTS_FAILED -eq 0 ] && [ $FAILED -eq 0 ]; then
    printf '%b\n' "${GREEN}✓ All complexity checks passed${NC}"
    exit 0
fi

printf '%s\n' ""
if [ $NOT_ANALYSED -eq 1 ]; then
    printf '%b\n' "${RED}Commit rejected: knots could not analyse every staged file${NC}"
    printf '%s\n' "Fix the file, or leave it out of the commit."
fi
if [ $KNOTS_FAILED -eq 1 ]; then
    printf '%b\n' "${RED}Commit rejected: knots' own check failed; see its messages above${NC}"
fi
if [ $FAILED -eq 1 ]; then
    printf '%b\n' "${RED}Commit rejected: Complexity thresholds exceeded${NC}"
    printf '%s\n' ""
    printf '%s\n' "To adjust thresholds, run:"
    printf '%s\n' "  git config hooks.knots.mccabe-threshold <value>"
    printf '%s\n' "  git config hooks.knots.cognitive-threshold <value>"
    printf '%s\n' "  git config hooks.knots.nesting-threshold <value>"
    printf '%s\n' "  git config hooks.knots.sloc-threshold <value>"
    printf '%s\n' "  git config hooks.knots.abc-threshold <value>"
    printf '%s\n' "  git config hooks.knots.return-threshold <value>"
fi
printf '%s\n' ""
printf '%s\n' "To bypass this check (not recommended), use:"
printf '%s\n' "  git commit --no-verify"
exit 1
