#!/bin/sh
#
# Pre-commit hook for knots (WARNING MODE)
# Reports the complexity of every staged file knots can analyse, but doesn't block commits
#
# Installation:
#   cp pre-commit-warning-only .git/hooks/pre-commit
#   chmod +x .git/hooks/pre-commit
#

# Configuration
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)}

# Colors
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
NC='\033[0m'

# 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-
}

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
    exit 0
fi

# Warning mode never blocks, but says when nothing was checked.
if [ ! -x "$VALIDATOR_PATH" ]; then
    printf '%b\n' "${YELLOW}Warning: knots not found${VALIDATOR_PATH:+ at $VALIDATOR_PATH}; staged files were not checked${NC}" >&2
    printf '%s\n' "Install it or set the path with: git config hooks.knots.path /path/to/knots" >&2
    exit 0
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' "Checking complexity of staged files..."
printf '%s\n' ""

WARNINGS=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' "$YELLOW" "⚠ $file: knots' own check failed (exit 1); see the knots: lines above" "$NC"
            KNOTS_FAILED=$((KNOTS_FAILED + 1))
            ;;
        *)
            printf '%b%s%b\n' "$YELLOW" "⚠ $file: not analysed (knots exited $STATUS)" "$NC"
            NOT_ANALYSED=$((NOT_ANALYSED + 1))
            continue
            ;;
    esac

    while IFS="$TAB" read -r label message; do
        [ -n "$label" ] || continue
        printf '%b%s%b\n' "$YELLOW" "⚠ $label" "$NC"
        printf '%s\n' "  $message"
        WARNINGS=$((WARNINGS + 1))
    done <<EOF
$(breaches "$OUTPUT")
EOF
done <<FILES
$C_FILES
FILES

if [ $NOT_ANALYSED -gt 0 ]; then
    printf '%s\n' ""
    printf '%b\n' "${YELLOW}knots could not analyse $NOT_ANALYSED staged file(s)${NC}"
fi
if [ $KNOTS_FAILED -gt 0 ]; then
    printf '%s\n' ""
    printf '%b\n' "${YELLOW}knots' own check failed for $KNOTS_FAILED staged file(s)${NC}"
fi
if [ $WARNINGS -gt 0 ]; then
    printf '%s\n' ""
    printf '%b\n' "${YELLOW}Found $WARNINGS complexity warning(s) - consider refactoring${NC}"
elif [ $NOT_ANALYSED -eq 0 ] && [ $KNOTS_FAILED -eq 0 ]; then
    printf '%b\n' "${GREEN}✓ All complexity checks passed${NC}"
fi

# Always succeed (warning mode)
exit 0
