#!/bin/bash

# Fast Pre-Commit Script for Wasot Compiler
# Optimized for speed while maintaining quality
# Run this before every commit to ensure code quality

set -e

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

# Timing
START_TIME=$(date +%s)

echo -e "${BLUE}🚀 Pre-Commit Quality Checks${NC}"
echo "============================="

# Check if we're in the right directory
if [ ! -f "Cargo.toml" ]; then
    echo -e "${RED}❌ Error: This script must be run from the project root directory${NC}"
    exit 1
fi

# Track overall success
OVERALL_SUCCESS=0

# Function to run a check and track results with timing
run_check() {
    local name="$1"
    local cmd="$2"
    local fix_cmd="$3"
    local start_check_time=$(date +%s)
    
    echo ""
    echo -e "${BLUE}🔍 $name${NC}"
    
    if eval "$cmd" > /tmp/precommit_output 2>&1; then
        local end_check_time=$(date +%s)
        local duration=$((end_check_time - start_check_time))
        echo -e "${GREEN}✅ $name: PASSED${NC} (${duration}s)"
    else
        local end_check_time=$(date +%s)
        local duration=$((end_check_time - start_check_time))
        echo -e "${RED}❌ $name: FAILED${NC} (${duration}s)"
        cat /tmp/precommit_output
        OVERALL_SUCCESS=1
        if [ -n "$fix_cmd" ]; then
            echo -e "${YELLOW}🔧 To fix: $fix_cmd${NC}"
        fi
    fi
}

# Function to auto-fix issues
auto_fix() {
    local name="$1"
    local cmd="$2"
    local start_fix_time=$(date +%s)
    
    echo ""
    echo -e "${YELLOW}🔧 Auto-fixing: $name${NC}"
    
    if eval "$cmd" > /tmp/precommit_fix_output 2>&1; then
        local end_fix_time=$(date +%s)
        local duration=$((end_fix_time - start_fix_time))
        echo -e "${GREEN}✅ $name: FIXED${NC} (${duration}s)"
    else
        local end_fix_time=$(date +%s)
        local duration=$((end_fix_time - start_fix_time))
        echo -e "${RED}❌ $name: FIX FAILED${NC} (${duration}s)"
        cat /tmp/precommit_fix_output
        OVERALL_SUCCESS=1
    fi
}

# 1. Run existing test script
run_check "Basic Tests" \
    "./scripts/testing/test.sh > /dev/null 2>&1"

# 2. Auto-fix formatting issues
auto_fix "Code Formatting" \
    "cargo fmt --all"

# 3. Auto-fix safe clippy issues
auto_fix "Safe Clippy Fixes" \
    "cargo clippy --all-targets --features "sqlite" --fix --allow-dirty --allow-staged"

# 4. Auto-fix compiler suggestions
auto_fix "Compiler Suggestions" \
    "cargo fix --all-targets --allow-dirty --allow-staged"

# 5. Check that everything still compiles after fixes
run_check "Compilation Check" \
    "cargo check --all-targets --features "sqlite""

# 6. Run clippy again to check for remaining issues
run_check "Clippy Linting" \
    "cargo clippy --all-targets --features "sqlite" -- -D warnings" \
    "cargo clippy --all-targets --features "sqlite" --fix"

# 7. Fast test run (only if code compiled successfully)
if [ $OVERALL_SUCCESS -eq 0 ]; then
    run_check "Unit Tests" \
        "cargo test --features "sqlite" --quiet"
else
    echo -e "${YELLOW}⏭️  Skipping tests due to compilation failures${NC}"
fi

# 8. Check for common code quality issues (fast checks)
echo ""
echo -e "${BLUE}🔍 Quick Code Quality Checks${NC}"

# Check for TODO/FIXME comments in staged files
if command -v git &> /dev/null && git rev-parse --git-dir > /dev/null 2>&1; then
    STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '\.rs$' || true)
    if [ -n "$STAGED_FILES" ]; then
        TODO_COUNT=$(echo "$STAGED_FILES" | xargs grep -l "TODO\|FIXME\|XXX\|HACK" 2>/dev/null | wc -l || echo "0")
        if [ "$TODO_COUNT" -gt 0 ]; then
            echo -e "${YELLOW}⚠️  Found TODO/FIXME comments in staged files${NC}"
            echo "$STAGED_FILES" | xargs grep -n "TODO\|FIXME\|XXX\|HACK" 2>/dev/null | head -3 || true
        else
            echo -e "${GREEN}✅ No TODO/FIXME comments in staged files${NC}"
        fi
        
        # Check for debug prints in staged files
        DEBUG_COUNT=$(echo "$STAGED_FILES" | xargs grep -l "println!\|dbg!\|eprintln!" 2>/dev/null | grep -v test | wc -l || echo "0")
        if [ "$DEBUG_COUNT" -gt 0 ]; then
            echo -e "${YELLOW}⚠️  Found debug prints in staged files${NC}"
            echo "$STAGED_FILES" | xargs grep -n "println!\|dbg!\|eprintln!" 2>/dev/null | grep -v test | head -3 || true
        else
            echo -e "${GREEN}✅ No debug prints in staged files${NC}"
        fi
    fi
fi

# 9. Security check (only if cargo-audit is available and fast)
if command -v cargo-audit &> /dev/null; then
    run_check "Security Audit" \
        "timeout 10s cargo audit || exit 0" \
        "cargo update (check for security advisories)"
fi

# 10. Final formatting check
run_check "Final Format Check" \
    "cargo fmt --all -- --check" \
    "cargo fmt --all"

# Calculate total time
END_TIME=$(date +%s)
TOTAL_TIME=$((END_TIME - START_TIME))

# Final Summary
echo ""
echo -e "${BLUE}🎯 Pre-Commit Summary${NC}"
echo "====================="
echo -e "⏱️  Total time: ${TOTAL_TIME}s"

if [ $OVERALL_SUCCESS -eq 0 ]; then
    echo -e "${GREEN}🎉 All pre-commit checks passed!${NC}"
    echo ""
    echo -e "${GREEN}✅ Ready to commit:${NC}"
    echo "   - Code formatted correctly"
    echo "   - No clippy warnings"
    echo "   - All tests passing"
    echo "   - Compilation successful"
    echo ""
    echo -e "${BLUE}💡 Next steps:${NC}"
    echo "   git add ."
    echo "   git commit -m 'Your commit message'"
else
    echo -e "${RED}❌ Some pre-commit checks failed!${NC}"
    echo ""
    echo -e "${YELLOW}🔧 To fix all issues automatically:${NC}"
    echo "   ./scripts/ci/fix_all.sh"
    echo ""
    echo -e "${YELLOW}🔍 For detailed analysis:${NC}"
    echo "   ./scripts/ci/linter.sh"
fi

# Show changed files if in git repo
if command -v git &> /dev/null && git rev-parse --git-dir > /dev/null 2>&1; then
    CHANGED_FILES=$(git diff --name-only HEAD 2>/dev/null || true)
    if [ -n "$CHANGED_FILES" ]; then
        echo ""
        echo -e "${BLUE}📝 Modified files:${NC}"
        echo "$CHANGED_FILES" | sed 's/^/   /'
    fi
fi

# Cleanup
rm -f /tmp/precommit_output /tmp/precommit_fix_output

echo ""
echo -e "${BLUE}🚀 Pre-commit checks completed in ${TOTAL_TIME}s${NC}"

exit $OVERALL_SUCCESS