#!/usr/bin/env bash
set -euo pipefail

REMOTE="$1"
URL="$2"
LOCAL_REF="$3"
LOCAL_SHA="$4"
REMOTE_REF="$5"
REMOTE_SHA="$6"

RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
NC='\033[0m'

BRANCH=$(git rev-parse --abbrev-ref HEAD)

echo "── Pre-push checks for branch: $BRANCH ──"

# 1. Validate branch naming (skip main/master)
if [ "$BRANCH" != "main" ] && [ "$BRANCH" != "master" ] && [ "$BRANCH" != "develop" ]; then
    if ! echo "$BRANCH" | grep -qE '^(feature|fix|chore|hotfix|release|docs)/'; then
        echo ""
        echo -e "${RED}✗ Invalid branch name: $BRANCH${NC}"
        echo "  Branch names must follow: type/description"
        echo "  Valid prefixes: feature/, fix/, chore/, hotfix/, release/, docs/"
        echo "  Example: feature/add-login-page"
        echo ""
        echo "  To rename: git branch -m $BRANCH feature/$BRANCH"
        exit 1
    fi
    echo -e "${GREEN}✓ Branch name valid${NC}"
fi

# 2. Check for uncommitted changes
if ! git diff --quiet; then
    echo -e "${YELLOW}⚠ Uncommitted changes detected${NC}"
fi

# 3. Run tests if test script exists
if [ -f "package.json" ] && command -v npm &>/dev/null; then
    if grep -q '"test"' package.json; then
        echo "  Running tests..."
        if ! npm test -- --silent 2>&1 | tail -5; then
            # Only warn, don't block
            echo -e "${YELLOW}⚠ Tests failed (not blocking push)${NC}"
        else
            echo -e "${GREEN}✓ Tests passed${NC}"
        fi
    fi
elif [ -f "Makefile" ] && grep -q '^test:' Makefile; then
    echo "  Running tests..."
    if ! make test 2>&1 | tail -5; then
        echo -e "${YELLOW}⚠ Tests failed (not blocking push)${NC}"
    else
        echo -e "${GREEN}✓ Tests passed${NC}"
    fi
fi

echo -e "${GREEN}✓ Pre-push checks complete${NC}"
exit 0
