#!/bin/bash

# SPDX-FileCopyrightText: Copyright (C) 2025 Advanced Micro Devices, Inc. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

set -e

echo "Running pre-push linting checks..."
echo "===================================="

# Check if we're in the right directory
if [ ! -f "scripts/clang-format-wrapper.py" ]; then
    echo "Error: Must be run from repository root"
    exit 1
fi

# Track if any checks fail
FAILED=0

# Check Licenses
echo ""
echo "Checking licenses with reuse..."
if command -v reuse &> /dev/null; then
    if ! reuse lint; then
        echo "❌ License check failed"
        echo '   Run: reuse annotate --template ApacheAMD --copyright-prefix spdx-string-c --copyright "Advanced Micro Devices, Inc. All rights reserved." --license="Apache-2.0" --recursive --skip-unrecognised ./'
        FAILED=1
    else
        echo "✅ License check passed"
    fi
else
    echo "⚠️  Warning: reuse not installed, skipping license check"
    echo "   Install with: pip install reuse"
fi

# Format Python
echo ""
echo "Checking Python formatting with black..."
if command -v black &> /dev/null; then
    if ! black --check . 2>&1 | grep -v "would reformat" | grep -v "files would be left unchanged"; then
        echo "❌ Python formatting check failed"
        echo "   Run: black ."
        FAILED=1
    else
        echo "✅ Python formatting check passed"
    fi
else
    echo "⚠️  Warning: black not installed, skipping Python format check"
    echo "   Install with: pip install black"
fi

# Format C++
echo ""
echo "Checking C++ formatting with clang-format..."
if command -v clang-format &> /dev/null; then
    if ! python scripts/clang-format-wrapper.py --check; then
        echo "❌ C++ formatting check failed"
        echo "   Run: python scripts/clang-format-wrapper.py --fix"
        FAILED=1
    else
        echo "✅ C++ formatting check passed"
    fi
else
    echo "⚠️  Warning: clang-format not installed, skipping C++ format check"
    echo "   Install with: apt-get install clang-format (or equivalent)"
fi

echo ""
echo "===================================="

if [ $FAILED -eq 1 ]; then
    echo "❌ Pre-push checks FAILED"
    echo ""
    echo "Please fix the issues above before pushing."
    echo "To bypass this hook (not recommended), use: git push --no-verify"
    exit 1
else
    echo "✅ All pre-push checks PASSED"
    echo ""
fi

exit 0
