#!/usr/bin/env bash

# Pre-commit hook for Swift code style checks
# Only checks staged Swift files for fast feedback

set -euo pipefail

export PATH="$PATH:/opt/homebrew/bin:/opt/homebrew/sbin"

# Get the repository root
REPO_ROOT=$(git rev-parse --show-toplevel)
MACOS_DIR="$REPO_ROOT/macos"
SCRIPT_DIR="$REPO_ROOT/.githooks"

# Get staged Swift files in macos
STAGED_SWIFT_FILES=$(git diff --cached --name-only --diff-filter=ACM 2>/dev/null | grep '^macos/.*\.swift$' || true)

if [[ -z "$STAGED_SWIFT_FILES" ]]; then
    echo "[pre-commit] No staged Swift files to check."
    exit 0
fi

echo "[pre-commit] Checking $(echo "$STAGED_SWIFT_FILES" | wc -l | tr -d ' ') staged Swift file(s)..."

targets_file=$(mktemp "${TMPDIR:-/tmp}/openbridge-swift-lint-targets.XXXXXX")
trap 'rm -f "$targets_file"' EXIT
printf '%s\n' "$STAGED_SWIFT_FILES" | sed 's#^macos/##' > "$targets_file"

cd "$MACOS_DIR"

echo "[pre-commit] Running shared Swift lint script..."
if ! SWIFT_LINT_TARGETS_FILE="$targets_file" DevKit/Scripts/swift_format_lint.sh --strict; then
    echo ""
    echo "[pre-commit] ❌ Swift code style checks failed."
    exit 1
fi

echo "[pre-commit] ✅ Swift code style checks passed!"
exit 0
