#!/bin/sh
# Pre-commit hook: validate Pine Script security call budget.
#
# Runs whenever a .pine file is staged. Uses count_pine_security_calls.py
# --strategy mode so library calls are followed and (symbol, tf) pairs are
# properly deduplicated against the 40-call TV limit.
#
# To skip in an emergency: git commit --no-verify

REPO="$(git rev-parse --show-toplevel)"
PYTHON="$REPO/.venv/bin/python3"

# Only run if any .pine files are staged
staged_pine=$(git diff --cached --name-only | grep '\.pine$')
[ -z "$staged_pine" ] && exit 0

STRATEGY_MLP="$REPO/strategies/strategy_mlp_scores.pine"
STRATEGY_ACT="$REPO/strategies/strategy_activation_scores.pine"

EXIT_CODE=0

check_strategy() {
    strategy_file="$1"
    label="$2"
    if [ ! -f "$strategy_file" ]; then
        return 0
    fi
    result=$("$PYTHON" "$REPO/tools/count_pine_security_calls.py" \
        --strategy "$strategy_file" --summary 2>&1)
    status=$?
    over=$(echo "$result" | grep "TOTAL unique" | grep -v "OK")
    if [ $status -ne 0 ] || [ -n "$over" ]; then
        echo "❌  Pine security call budget EXCEEDED in $label"
        echo "$result" | grep -E "TOTAL|remaining|❌" | head -5
        EXIT_CODE=1
    else
        count=$(echo "$result" | grep "TOTAL unique" | grep -oE '[0-9]+ / [0-9]+' | head -1)
        echo "✅  $label: $count unique security calls (≤40)"
    fi
}

echo "--- Pine security call budget check ---"
check_strategy "$STRATEGY_MLP" "strategy_mlp_scores.pine"
check_strategy "$STRATEGY_ACT" "strategy_activation_scores.pine"

if [ $EXIT_CODE -ne 0 ]; then
    echo ""
    echo "Fix: remove security calls from strategy or LibraryMoneySupply, then re-stage."
    echo "     Run: python3 tools/count_pine_security_calls.py --strategy <file>"
    echo "     To bypass (emergency only): git commit --no-verify"
fi

exit $EXIT_CODE
