#!/usr/bin/env bash
# Pre-commit hook to run ruff checks on staged Python files
# and Mintlify validation on staged documentation files
# Works on Linux, macOS, WSL, and Windows (Git Bash)

set -e

# Get the repository root directory
REPO_ROOT=$(git rev-parse --show-toplevel)

# Detect if we're being called from Windows to a WSL repo
# Check for \\wsl.localhost\ or /mnt/wsl/ patterns
if [[ "$REPO_ROOT" == *"wsl.localhost"* ]] || [[ "$REPO_ROOT" == *"\\wsl"* ]]; then
    echo "🔄 Detected Windows → WSL commit, delegating to WSL..."

    # Extract WSL path - convert \\wsl.localhost\Ubuntu\path to /path
    WSL_PATH=$(echo "$REPO_ROOT" | sed 's|.*wsl.localhost[/\\][^/\\]*||' | sed 's|\\|/|g')

    # Get staged Python files
    STAGED_PY_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(py)$' || true)

    # Get staged documentation files (MDX and docs.json)
    STAGED_DOC_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '^docs/.*\.(mdx|json)$' || true)

    if [ -z "$STAGED_PY_FILES" ] && [ -z "$STAGED_DOC_FILES" ]; then
        echo "No Python or documentation files staged for commit."
        exit 0
    fi

    if [ -n "$STAGED_PY_FILES" ]; then
        echo "Running ruff checks on staged Python files..."
        echo "Files to check:"
        echo "$STAGED_PY_FILES"
        echo ""

        # Convert newline-separated files to space-separated for proper passing
        STAGED_PY_FILES_ARGS=$(echo "$STAGED_PY_FILES" | tr '\n' ' ')

        # Execute in WSL - use full path to uv if it's in a standard location
        # Try common locations: ~/.cargo/bin/uv, /usr/local/bin/uv, or just 'uv' in PATH
        wsl.exe bash -l -c "cd '$WSL_PATH' && (command -v uv > /dev/null 2>&1 || export PATH=\"\$HOME/.cargo/bin:\$PATH\") && uv run ruff check $STAGED_PY_FILES_ARGS"
        CHECK_EXIT=$?

        if [ $CHECK_EXIT -ne 0 ]; then
            echo ""
            echo "❌ Ruff check failed!"
            echo "To fix issues, run in WSL terminal:"
            echo "  uv run ruff check --fix $STAGED_PY_FILES_ARGS"
            echo ""
            echo "To bypass (not recommended): git commit --no-verify"
            exit 1
        fi

        wsl.exe bash -l -c "cd '$WSL_PATH' && (command -v uv > /dev/null 2>&1 || export PATH=\"\$HOME/.cargo/bin:\$PATH\") && uv run ruff format --check $STAGED_PY_FILES_ARGS"
        FORMAT_EXIT=$?

        if [ $FORMAT_EXIT -ne 0 ]; then
            echo ""
            echo "❌ Ruff format check failed!"
            echo "To fix formatting, run in WSL terminal:"
            echo "  uv run ruff format $STAGED_PY_FILES_ARGS"
            echo ""
            echo "To bypass (not recommended): git commit --no-verify"
            exit 1
        fi

        echo "✅ All ruff checks passed!"
    fi

    if [ -n "$STAGED_DOC_FILES" ]; then
        echo "Documentation files staged — skipping slow mintlify checks in hook."
    fi

    exit 0
fi

# Native execution (Linux, macOS, or Git Bash on Windows)
# Get list of staged Python files
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(py)$' || true)

# Get staged documentation files (MDX and docs.json)
STAGED_DOC_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '^docs/.*\.(mdx|json)$' || true)

if [ -z "$STAGED_FILES" ] && [ -z "$STAGED_DOC_FILES" ]; then
    echo "No Python or documentation files staged for commit."
    exit 0
fi

if [ -n "$STAGED_FILES" ]; then
    echo "Running ruff checks on staged files..."
    echo "Files to check:"
    echo "$STAGED_FILES"
    echo ""
fi

# Normalize path for different environments
normalize_path() {
    local path="$1"

    # Check if path starts with /c/ or similar (Git Bash)
    if [[ "$path" =~ ^/[a-z]/ ]]; then
        echo "$path"
    # Check if path contains backslashes (Windows path)
    elif [[ "$path" == *\\* ]]; then
        echo "$path" | sed 's|\\|/|g'
    else
        echo "$path"
    fi
}

REPO_ROOT=$(normalize_path "$REPO_ROOT")

# Change to repo root
cd "$REPO_ROOT" || {
    echo "❌ Failed to change to repository root: $REPO_ROOT"
    exit 1
}

if [ -n "$STAGED_FILES" ]; then
    # Check if uv is available
    if ! command -v uv &> /dev/null; then
        echo "⚠️  uv not found in PATH."
        echo "Please install uv: https://docs.astral.sh/uv/getting-started/installation/"
        exit 1
    fi

    # Run ruff check on staged files using uv run
    echo "🔍 Running ruff check..."
    uv run ruff check $STAGED_FILES

    RUFF_CHECK_EXIT_CODE=$?

    if [ $RUFF_CHECK_EXIT_CODE -ne 0 ]; then
        echo ""
        echo "❌ Pre-commit hook failed!"
        echo "Ruff found linting issues in your staged files."
        echo ""
        echo "To fix issues automatically, run:"
        echo "  uv run ruff check --fix $STAGED_FILES"
        echo ""
        echo "Then stage the fixed files and commit again."
        echo ""
        echo "To bypass this hook (not recommended), use:"
        echo "  git commit --no-verify"
        exit 1
    fi

    # Run ruff format check on staged files
    echo "🎨 Running ruff format check..."
    uv run ruff format --check $STAGED_FILES

    RUFF_FORMAT_EXIT_CODE=$?

    if [ $RUFF_FORMAT_EXIT_CODE -ne 0 ]; then
        echo ""
        echo "❌ Pre-commit hook failed!"
        echo "Ruff found formatting issues in your staged files."
        echo ""
        echo "To fix formatting, run:"
        echo "  uv run ruff format $STAGED_FILES"
        echo ""
        echo "Then stage the fixed files and commit again."
        echo ""
        echo "To bypass this hook (not recommended), use:"
        echo "  git commit --no-verify"
        exit 1
    fi

    echo "✅ All ruff checks passed!"
fi

if [ -n "$STAGED_DOC_FILES" ]; then
    echo "Documentation files staged — skipping slow mintlify checks in hook."
fi

exit 0
