#!/usr/bin/env bash
# 𝓥𝓲𝓫𝓮𝓬𝓻𝓪𝓯𝓽𝓮𝓭. pre-commit hook
set -e

echo "⚒  Running pre-commit checks..."

STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM)

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

SH_FILES=()
PY_FILES=()
MD_YAML_FILES=()

while IFS= read -r file; do
    [ -z "$file" ] && continue
    case "$file" in
        *.sh|*.bash|*.zsh) SH_FILES+=("$file") ;;
        *.py) PY_FILES+=("$file") ;;
        *.md|*.yaml|*.yml) MD_YAML_FILES+=("$file") ;;
    esac
done <<< "$STAGED_FILES"

if [ ${#SH_FILES[@]} -gt 0 ]; then
    echo "▸ shellcheck (${#SH_FILES[@]} files)"
    python3 scripts/check_shell.py "${SH_FILES[@]}"
fi

if [ ${#PY_FILES[@]} -gt 0 ]; then
    echo "▸ ruff (${#PY_FILES[@]} files)"
    if command -v uvx >/dev/null 2>&1; then
        uvx ruff check --fix "${PY_FILES[@]}"
        uvx ruff format "${PY_FILES[@]}"
        git add "${PY_FILES[@]}"
    else
        echo "[warn] uvx unavailable; skipping ruff auto-fix"
    fi
fi

if [ ${#MD_YAML_FILES[@]} -gt 0 ]; then
    echo "▸ prettier (${#MD_YAML_FILES[@]} files)"
    npx --yes prettier --write "${MD_YAML_FILES[@]}"
    git add "${MD_YAML_FILES[@]}"
fi

echo "▸ semgrep"
if command -v semgrep >/dev/null 2>&1; then
    semgrep scan --config auto --error --quiet --exclude-rule html.security.audit.missing-integrity.missing-integrity
elif command -v uvx >/dev/null 2>&1; then
    uvx semgrep scan --config auto --error --quiet --exclude-rule html.security.audit.missing-integrity.missing-integrity
else
    echo "[warn] semgrep unavailable; skipping"
fi

echo "✓ Pre-commit passed"
