#!/bin/bash
# Pre-commit hook: CodeScene Code Health Check
# Copy to .git/hooks/pre-commit and make executable

set -e

# Allow bypass with --no-verify or [skip codescene] in commit message
if git log -1 --pretty=%B 2>/dev/null | grep -qi '\[skip codescene\]'; then
    echo "⏭️  CodeScene check skipped (commit message contains [skip codescene])"
    exit 0
fi

echo "🔍 Running CodeScene Code Health check..."

# Check if we have staged files to analyze
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(ts|tsx|rs)$' || true)

if [ -z "$STAGED_FILES" ]; then
    echo "✅ No TypeScript/Rust files staged, skipping CodeScene check"
    exit 0
fi

# Get current branch
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)

# Determine base branch for comparison
if [ "$CURRENT_BRANCH" = "main" ]; then
    BASE_REF="HEAD~1"
else
    BASE_REF="origin/main"
fi

echo "   Comparing against: $BASE_REF"

# Check if we have CodeScene configured (MCP or CLI)
CODESCENE_MCP_CONFIG="$HOME/.claude/mcp.json"
CODESCENE_TOKEN_FILE="$HOME/.codescene/token"

if [ ! -f "$CODESCENE_MCP_CONFIG" ] && [ ! -f "$CODESCENE_TOKEN_FILE" ]; then
    echo "⚠️  CodeScene not configured"
    echo "   Install CodeScene MCP (configured in ~/.claude/mcp.json)"
    echo "   Or place token at ~/.codescene/token"
    echo "   Proceeding without check (use 'git commit --no-verify' to skip this warning)"
    exit 0
fi

# Simple health check using git diff stats
echo "   Analyzing code changes..."

# Get file changes
LINES_ADDED=$(git diff --cached --numstat | awk '{sum+=$1} END {print sum}')
LINES_REMOVED=$(git diff --cached --numstat | awk '{sum+=$2} END {print sum}')

# Check for large files (potential complexity)
LARGE_FILES=$(git diff --cached --numstat | awk '$1 > 500 || $2 > 500 {print $3}')

if [ ! -z "$LARGE_FILES" ]; then
    echo "⚠️  Large file changes detected (>500 lines):"
    echo "$LARGE_FILES" | sed 's/^/   - /'
    echo ""
    echo "   Consider:"
    echo "   - Breaking into smaller commits"
    echo "   - Reviewing with Claude Code + CodeScene MCP"
    echo "   - Running: claude 'Review code health of staged changes'"
    echo ""
    read -p "   Continue anyway? (y/N) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "❌ Commit aborted"
        exit 1
    fi
fi

echo "✅ CodeScene check passed"
echo "   +$LINES_ADDED -$LINES_REMOVED lines"
echo ""
echo "   💡 For detailed code health analysis, run:"
echo "      claude 'Check code health of this commit with CodeScene MCP'"
echo ""

exit 0
