#!/usr/bin/env bash
# scankii pre-commit hook
# Scans staged .md, .py, .js, .ts files for credential leakage.
#
# Configuration (set these in your shell profile or .env):
#   SCANKII_SEVERITY_THRESHOLD — minimum severity to block commit (default: MEDIUM)
#   SCANKII_OUTPUT_PATH        — path for the findings JSON report (default: .scankii-report.json)
#
# Example: to only block on HIGH or above, add to your shell:
#   export SCANKII_SEVERITY_THRESHOLD=HIGH

set -euo pipefail

SEVERITY_THRESHOLD="${SCANKII_SEVERITY_THRESHOLD:-MEDIUM}"
OUTPUT_PATH="${SCANKII_OUTPUT_PATH:-.scankii-report.json}"

# Get list of staged files with relevant extensions
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(md|py|js|ts)$' || true)

if [ -z "$STAGED_FILES" ]; then
    exit 0
fi

# Create a temporary directory for staged files
TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT

# Copy staged files to temp directory preserving structure
for file in $STAGED_FILES; do
    dir=$(dirname "$file")
    mkdir -p "$TMPDIR/$dir"
    git show ":$file" > "$TMPDIR/$file" 2>/dev/null || true
done

# Run scankii scan
if ! command -v scankii &> /dev/null; then
    echo "⚠️  scankii not installed. Run: pip install scankii"
    exit 0
fi

# Use --severity-threshold to control what blocks commits
# Use --output to write report to a consistent, explicit path
scankii scan "$TMPDIR" \
    --format json \
    --output "$OUTPUT_PATH" \
    --severity-threshold "$SEVERITY_THRESHOLD" \
    2>/dev/null

SCAN_EXIT=$?

if [ $SCAN_EXIT -ne 0 ]; then
    echo "❌ scankii: Findings at or above $SEVERITY_THRESHOLD severity detected."
    echo "   Report: $OUTPUT_PATH"
    echo "   Run 'scankii scan . --format terminal' for full details."
    echo "   To adjust the threshold: export SCANKII_SEVERITY_THRESHOLD=HIGH"
    exit 1
fi

echo "✅ scankii: No findings at or above $SEVERITY_THRESHOLD severity."
