#!/bin/sh
# Find potentially unused static functions in C source files
# Usage: ./.claude/scripts/find-unused-statics.sh

set -e

echo "Searching for potentially unused static functions...\n"

# Generate ctags for static functions
TMPFILE=$(mktemp)
trap "rm -f $TMPFILE" EXIT

ctags --format=2 --fields=kKn --c-kinds=f -o "$TMPFILE" \
  $(find src pim -name "*.c" 2>/dev/null) 2>/dev/null

# For each static function, check if it's called elsewhere
awk -F'\t' '
  NF >= 4 {
    name=$1
    file=$2
    # Extract just the function name (in case it has parameters)
    gsub(/\(.*/, "", name)
    funcs[name] = file
  }
  END {
    print "Checking " length(funcs) " static functions for usage...\n"
    unused = 0
    for (func in funcs) {
      # Search for calls to this function (word boundary, not definition)
      cmd = "grep -r \"" func "(\" src pim 2>/dev/null | grep -v \"^Binary\" | wc -l"
      cmd | getline count
      close(cmd)

      # If found only once (the definition), it might be unused
      if (count <= 1) {
        unused++
        if (unused == 1) print "Potentially unused functions:\n"
        print "  " func " (in " funcs[func] ")"
      }
    }

    if (unused == 0) {
      print "All static functions appear to be used."
    } else {
      print "\nNote: This is heuristic-based. Some may be false positives."
    }
  }
' "$TMPFILE"
