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

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

ALL_FILES=$(git ls-files)

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

# pre-push is a pure GATE: it verifies formatting (ruff/prettier --check) but
# never rewrites or re-stages. Auto-formatting belongs to pre-commit, which runs
# on the staged set. Rewriting the full working tree here would mutate
# uncommitted files unrelated to the push (e.g. a dirty doc you never staged).
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 <<< "$ALL_FILES"

echo "▸ vc_frame pane targeting guard"
leaks="$(
    grep -nE 'vc_frame[^|]*action new-pane' runtime/scripts/lib/*.sh 2>/dev/null \
        | grep -vE 'tab-id|tab_id|--floating|# OPERATOR_TAB_OK' \
        || true
)"
if [[ -n "$leaks" ]]; then
    printf 'pre-push: vc_frame new-pane without --tab-id / --floating / OPERATOR_TAB_OK marker:\n%s\n' "$leaks" >&2
    exit 1
fi

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

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

if [ ${#MD_YAML_FILES[@]} -gt 0 ]; then
    echo "▸ prettier (full, check-only)"
    npx --yes prettier --check "${MD_YAML_FILES[@]}"
fi

echo "▸ semgrep (full)"
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-push passed"
