#!/bin/bash

# Linter Script for Wasot Compiler
# Comprehensive code quality and style checking

set -e

echo "🔍 Linting Wasot Compiler"
echo "========================="

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

# Track overall success
OVERALL_SUCCESS=0

# Function to run a check and track results
run_check() {
    local name="$1"
    local cmd="$2"
    local fix_cmd="$3"
    
    echo ""
    echo "🔍 $name"
    echo "$(printf '%.0s-' {1..50})"
    
    if eval "$cmd"; then
        echo "✅ $name: PASSED"
    else
        echo "❌ $name: FAILED"
        OVERALL_SUCCESS=1
        if [ -n "$fix_cmd" ]; then
            echo "🔧 To fix: $fix_cmd"
        fi
    fi
}

# 1. Cargo Format Check
run_check "Code Formatting" \
    "cargo fmt --all -- --check" \
    "cargo fmt --all"

# 2. Clippy Linting
run_check "Clippy Linting (Pedantic)" \
    "cargo clippy --all-targets --all-features -- -D warnings -W clippy::pedantic" \
    "cargo clippy --all-targets --all-features --fix"

# 3. Cargo Check
run_check "Cargo Check" \
    "cargo check --all-targets --all-features"

# 4. Unused Dependencies
if command -v cargo-machete &> /dev/null; then
    run_check "Unused Dependencies" \
        "cargo machete" \
        "Remove unused dependencies from Cargo.toml"
else
    echo "📦 Installing cargo-machete for unused dependency checking..."
    cargo install cargo-machete
    run_check "Unused Dependencies" \
        "cargo machete" \
        "Remove unused dependencies from Cargo.toml"
fi

# 5. Security Audit
if command -v cargo-audit &> /dev/null; then
    run_check "Security Audit" \
        "cargo audit" \
        "Update dependencies with security vulnerabilities"
else
    echo "📦 Installing cargo-audit for security checking..."
    cargo install cargo-audit
    run_check "Security Audit" \
        "cargo audit" \
        "Update dependencies with security vulnerabilities"
fi

# 6. Outdated Dependencies
if command -v cargo-outdated &> /dev/null; then
    run_check "Outdated Dependencies Check" \
        "cargo outdated --exit-code 1" \
        "Update outdated dependencies"
else
    echo "📦 Installing cargo-outdated for dependency freshness checking..."
    cargo install cargo-outdated
    run_check "Outdated Dependencies Check" \
        "cargo outdated --exit-code 1" \
        "Update outdated dependencies"
fi

# 7. Documentation Check
run_check "Documentation Check" \
    "cargo doc --all --no-deps --document-private-items" \
    "Fix documentation warnings"

# 8. Test Compilation
run_check "Test Compilation" \
    "cargo test --no-run --all-features"

# 9. Benchmark Compilation (if benchmarks exist)
if grep -q "\\[\\[bench\\]\\]" Cargo.toml; then
    run_check "Benchmark Compilation" \
        "cargo bench --no-run"
fi

# 10. Check for TODO/FIXME comments
echo ""
echo "🔍 Code Quality Checks"
echo "$(printf '%.0s-' {1..50})"

TODO_COUNT=$(grep -r "TODO\|FIXME\|XXX\|HACK" src/ --include="*.rs" | wc -l)
if [ "$TODO_COUNT" -gt 0 ]; then
    echo "⚠️  Found $TODO_COUNT TODO/FIXME comments:"
    grep -r "TODO\|FIXME\|XXX\|HACK" src/ --include="*.rs" --color=always | head -10
    if [ "$TODO_COUNT" -gt 10 ]; then
        echo "   ... and $(($TODO_COUNT - 10)) more"
    fi
else
    echo "✅ No TODO/FIXME comments found"
fi

# 11. Check for panic! usage
PANIC_COUNT=$(grep -r "panic!\|unwrap()\|expect(" src/ --include="*.rs" | wc -l)
if [ "$PANIC_COUNT" -gt 0 ]; then
    echo "⚠️  Found $PANIC_COUNT potential panic sources:"
    grep -r "panic!\|unwrap()\|expect(" src/ --include="*.rs" --color=always | head -5
    if [ "$PANIC_COUNT" -gt 5 ]; then
        echo "   ... and $(($PANIC_COUNT - 5)) more"
    fi
    echo "💡 Consider using Result<T, E> for error handling"
else
    echo "✅ No obvious panic sources found"
fi

# 12. Check for debug prints
DEBUG_COUNT=$(grep -r "println!\|dbg!\|eprintln!" src/ --include="*.rs" | grep -v "test" | wc -l)
if [ "$DEBUG_COUNT" -gt 0 ]; then
    echo "⚠️  Found $DEBUG_COUNT debug print statements:"
    grep -r "println!\|dbg!\|eprintln!" src/ --include="*.rs" --color=always | grep -v "test" | head -5
    if [ "$DEBUG_COUNT" -gt 5 ]; then
        echo "   ... and $(($DEBUG_COUNT - 5)) more"
    fi
    echo "💡 Consider using log macros instead of println!"
else
    echo "✅ No debug print statements found"
fi

# 13. License Check
if [ -f "LICENSE" ] || [ -f "LICENSE.txt" ] || [ -f "LICENSE.md" ]; then
    echo "✅ License file found"
else
    echo "⚠️  No license file found"
    echo "💡 Consider adding a LICENSE file"
fi

# 14. Check Cargo.toml metadata
echo ""
echo "🔍 Cargo.toml Metadata Check"
echo "$(printf '%.0s-' {1..50})"

if grep -q "^description = " Cargo.toml; then
    echo "✅ Package description found"
else
    echo "⚠️  Package description missing"
    OVERALL_SUCCESS=1
fi

if grep -q "^license = " Cargo.toml; then
    echo "✅ Package license specified"
else
    echo "⚠️  Package license missing"
    OVERALL_SUCCESS=1
fi

if grep -q "^repository = " Cargo.toml; then
    echo "✅ Repository URL specified"
else
    echo "⚠️  Repository URL missing"
fi

if grep -q "^keywords = " Cargo.toml; then
    echo "✅ Keywords specified"
else
    echo "⚠️  Keywords missing"
fi

if grep -q "^categories = " Cargo.toml; then
    echo "✅ Categories specified"
else
    echo "⚠️  Categories missing"
fi

# 15. Final Summary
echo ""
echo "🎯 Linting Summary"
echo "=================="

if [ $OVERALL_SUCCESS -eq 0 ]; then
    echo "✅ All linting checks passed!"
    echo ""
    echo "🎉 Your code meets high quality standards!"
else
    echo "❌ Some linting checks failed!"
    echo ""
    echo "🔧 Fix the issues above to improve code quality."
fi

echo ""
echo "💡 Additional Tools to Consider:"
echo "   - cargo-deny: Advanced dependency checking"
echo "   - cargo-geiger: Unsafe code detection"
echo "   - cargo-expand: Macro expansion debugging"
echo "   - cargo-bloat: Binary size analysis"
echo ""
echo "🔧 Quick fixes:"
echo "   cargo fmt --all                    # Format code"
echo "   cargo clippy --all-targets --fix   # Fix clippy issues"
echo "   cargo fix --all-targets            # Fix compiler suggestions"
echo ""

exit $OVERALL_SUCCESS