#!/bin/bash

# Pre-commit hook for quickcall-integrations
# Blocks certain files and runs linters

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${YELLOW}Running pre-commit checks...${NC}"

# ============================================
# 1. Block sensitive/local-only files
# ============================================
BLOCKED_FILES="CLAUDE.md PLAN.md"

for file in $BLOCKED_FILES; do
    if git diff --cached --name-only | grep -q "^${file}$"; then
        echo -e "${RED}ERROR: Cannot commit ${file} - this file should remain local only${NC}"
        echo -e "Run: git reset HEAD ${file}"
        exit 1
    fi
done

# ============================================
# 2. Python linting (if Python files staged)
# ============================================
PYTHON_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '\.py$' || true)

if [ -n "$PYTHON_FILES" ]; then
    echo -e "${YELLOW}Checking Python files...${NC}"

    # Check if ruff is available
    if command -v ruff &> /dev/null; then
        echo "$PYTHON_FILES" | xargs ruff check --fix
        echo "$PYTHON_FILES" | xargs ruff format
        # Re-add any auto-fixed files
        echo "$PYTHON_FILES" | xargs git add
    else
        echo -e "${YELLOW}Warning: ruff not found, skipping Python linting${NC}"
    fi
fi

# ============================================
# 3. TypeScript/JavaScript linting (if staged)
# ============================================
TS_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(ts|tsx|js|jsx)$' || true)

if [ -n "$TS_FILES" ]; then
    echo -e "${YELLOW}Checking TypeScript/JavaScript files...${NC}"

    # Check for eslint config and node_modules
    if [ -f "packages/web/node_modules/.bin/eslint" ] && [ -f "packages/web/eslint.config.js" ]; then
        cd packages/web
        echo "$TS_FILES" | xargs npx eslint --fix 2>/dev/null || true
        cd ../..
        echo "$TS_FILES" | xargs git add 2>/dev/null || true
    else
        echo -e "${YELLOW}Warning: eslint not configured, skipping TS/JS linting${NC}"
    fi
fi

# ============================================
# 4. Check for debug statements
# ============================================
if git diff --cached | grep -E '(console\.log|print\(|debugger|import pdb)' | grep -v '#.*noqa' > /dev/null; then
    echo -e "${YELLOW}Warning: Found debug statements in staged changes${NC}"
    echo -e "Consider removing console.log, print(), debugger, or pdb imports"
    # Not blocking, just warning
fi

echo -e "${GREEN}Pre-commit checks passed!${NC}"
exit 0
