#!/usr/bin/env bash
set -e

echo "========================================"
echo "⚡ Fast Pre-Commit Tests & Coverage"
echo "========================================"

# Pre-commit passes staged files as arguments
STAGED_FILES="$@"
TEST_TARGETS=""

if [ -z "$STAGED_FILES" ]; then
    echo "No files provided. Running default unit tests."
    TEST_TARGETS="tests/unit"
else
    for file in $STAGED_FILES; do
        if [[ "$file" == tests/* ]]; then
            TEST_TARGETS="$TEST_TARGETS $file"
        elif [[ "$file" == GramAddict/* ]]; then
            filename=$(basename "$file")
            # Heuristic: Try to find a matching unit test
            test_file="tests/unit/test_${filename}"
            if [ -f "$test_file" ]; then
                TEST_TARGETS="$TEST_TARGETS $test_file"
            else
                # If no direct unit test, fallback to running all unit tests to be safe
                echo "⚠️ No direct unit test found for $file, falling back to all unit tests."
                TEST_TARGETS="tests/unit"
                break
            fi
        fi
    done
fi

# Trim whitespace
TEST_TARGETS=$(echo "$TEST_TARGETS" | xargs)

if [ -z "$TEST_TARGETS" ]; then
    echo "No Python files changed that require testing. Skipping."
    exit 0
fi

echo "🧪 Running tests on: $TEST_TARGETS"
venv/bin/pytest $TEST_TARGETS --cov=GramAddict --cov-report=xml -q

echo ""
echo "========================================"
echo "🛡️  Checking Coverage of NEW lines (diff-cover)"
echo "========================================"

# Check if origin/main exists, otherwise use main or HEAD
COMPARE_BRANCH="origin/main"
if ! git rev-parse --verify "$COMPARE_BRANCH" >/dev/null 2>&1; then
    COMPARE_BRANCH="main"
fi
if ! git rev-parse --verify "$COMPARE_BRANCH" >/dev/null 2>&1; then
    COMPARE_BRANCH="HEAD"
fi

# Run diff-cover requiring 30% coverage on new/changed lines
venv/bin/diff-cover coverage.xml --compare-branch=$COMPARE_BRANCH --fail-under=25

echo "✅ All targeted tests passed and coverage is sufficient on new lines!"
