#!/bin/bash

# ============================================================================
# ENTERPRISE LOG FORENSICS ANALYZER - VISUALIZATION EDITION
# Shows EXACT problems with actionable solutions + VISUALIZATION
# ============================================================================

# Configuration
VERSION="5.0.0"
ANALYSIS_TIMESTAMP=$(date +"%Y-%m-%dT%H:%M:%S%z")
SESSION_ID="$(date +%s)-$(head -c4 /dev/urandom | xxd -p)"
REPORT_DIR="/tmp/log_analysis_${SESSION_ID}"
HTML_REPORT="${REPORT_DIR}/dashboard.html"

# ANSI Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
NC='\033[0m' # No Color
BOLD='\033[1m'
UNDERLINE='\033[4m'

# Global Arrays
declare -A PROBLEMS
declare -A SOLUTIONS
declare -A ERROR_SOURCES
declare -A SERVICE_STATUS
declare -A TOP_ERRORS

# ============================================================================
# ORIGINAL ANALYSIS FUNCTIONS (from your original script)
# ============================================================================

analyze_syslog_with_details() {
    local file="$1"
    
    echo -e "\n${BLUE}${BOLD}🔍 DEEP ANALYSIS: $(basename "$file")${NC}"
    echo -e "${CYAN}=================================================================${NC}"
    
    # Reset arrays
    PROBLEMS=()
    SOLUTIONS=()
    ERROR_SOURCES=()
    SERVICE_STATUS=()
    TOP_ERRORS=()
    
    # 1. GET OVERALL STATS
    local total_lines=$(wc -l < "$file" 2>/dev/null || echo "0")
    echo -e "${WHITE}📊 Total log entries: $total_lines${NC}"
    
    # 2. FIND EXACT ERRORS WITH CONTEXT
    echo -e "\n${YELLOW}${BOLD}🚨 ERROR ANALYSIS - SHOWING EXACT PROBLEMS:${NC}"
    analyze_errors_with_context "$file"
    
    # 3. ANALYZE SERVICE FAILURES
    echo -e "\n${YELLOW}${BOLD}🔧 SERVICE HEALTH ANALYSIS:${NC}"
    analyze_service_health "$file"
    
    # 4. CHECK SYSTEM RESOURCES
    echo -e "\n${YELLOW}${BOLD}💾 SYSTEM RESOURCE ISSUES:${NC}"
    analyze_resource_issues "$file"
    
    # 5. SECURITY EVENTS
    echo -e "\n${YELLOW}${BOLD}🛡️  SECURITY EVENTS:${NC}"
    analyze_security_events "$file"
    
    # 6. NETWORK ISSUES
    echo -e "\n${YELLOW}${BOLD}🌐 NETWORK PROBLEMS:${NC}"
    analyze_network_issues "$file"
    
    # 7. GENERATE ACTIONABLE REPORT
    echo -e "\n${GREEN}${BOLD}════════════════════════════════════════════════════════════${NC}"
    echo -e "${GREEN}${BOLD}               ACTIONABLE DIAGNOSIS REPORT                   ${NC}"
    echo -e "${GREEN}${BOLD}════════════════════════════════════════════════════════════${NC}"
    
    generate_detailed_report
}

analyze_errors_with_context() {
    local file="$1"
    
    # Count total errors
    local error_lines=$(grep -n -i "error\|failed\|fail" "$file")
    local error_count=$(echo "$error_lines" | wc -l)
    
    echo -e "${RED}❌ Total errors found: $error_count${NC}"
    
    if [[ $error_count -eq 0 ]]; then
        echo -e "${GREEN}✓ No errors detected${NC}"
        return
    fi
    
    # Group errors by type and source
    echo -e "\n${CYAN}📋 Error Categories:${NC}"
    
    # Kernel errors
    local kernel_errors=$(grep -i "kernel.*error\|kernel.*fail" "$file" | head -5)
    local kernel_count=$(echo "$kernel_errors" | wc -l)
    if [[ $kernel_count -gt 0 ]]; then
        echo -e "${RED}   • Kernel Errors: $kernel_count${NC}"
        PROBLEMS["kernel_errors"]="$kernel_count"
        SOLUTIONS["kernel_errors"]="1. Check dmesg for details: sudo dmesg | grep -i error\n   2. Update kernel if needed\n   3. Check hardware with: sudo smartctl -a /dev/sda"
        
        # Show sample kernel errors
        echo -e "${YELLOW}   Sample kernel errors:${NC}"
        echo "$kernel_errors" | head -3 | while read -r line; do
            echo -e "     ${WHITE}→ ${line:0:150}...${NC}"
        done
    fi
    
    # Service errors
    echo -e "\n${CYAN}🔍 Service-Specific Errors:${NC}"
    
    # Systemd service failures
    local systemd_errors=$(grep -i "systemd.*failed\|Failed to start" "$file")
    local systemd_count=$(echo "$systemd_errors" | wc -l)
    if [[ $systemd_count -gt 0 ]]; then
        echo -e "${RED}   • Systemd Service Failures: $systemd_count${NC}"
        PROBLEMS["systemd_failures"]="$systemd_count"
        
        # Extract failing services
        local failing_services=$(echo "$systemd_errors" | grep -oP 'Failed to start \K[^ ]+' | sort -u)
        echo -e "${YELLOW}   Failing services:${NC}"
        for service in $failing_services; do
            echo -e "     ${WHITE}→ $service${NC}"
            SOLUTIONS["service_$service"]="sudo systemctl status $service\n   sudo journalctl -u $service -n 50\n   sudo systemctl restart $service"
        done
    fi
    
    # Disk errors
    local disk_errors=$(grep -i "disk.*error\|I/O error\|filesystem.*error\|EXT4-fs error" "$file")
    local disk_count=$(echo "$disk_errors" | wc -l)
    if [[ $disk_count -gt 0 ]]; then
        echo -e "${RED}   • Disk/FS Errors: $disk_count${NC}"
        PROBLEMS["disk_errors"]="$disk_count"
        SOLUTIONS["disk_errors"]="1. Check disk health: sudo smartctl -a /dev/sda\n   2. Check filesystem: sudo fsck -f /dev/sda1\n   3. Check disk space: df -h\n   4. Check I/O errors: dmesg | grep -i 'error'"
        
        echo -e "${YELLOW}   Sample disk errors:${NC}"
        echo "$disk_errors" | head -3 | while read -r line; do
            echo -e "     ${WHITE}→ ${line:0:120}...${NC}"
        done
    fi
    
    # Network errors
    local network_errors=$(grep -i "network.*error\|connection.*failed\|timeout" "$file")
    local network_count=$(echo "$network_errors" | wc -l)
    if [[ $network_count -gt 0 ]]; then
        echo -e "${RED}   • Network Errors: $network_count${NC}"
        PROBLEMS["network_errors"]="$network_count"
        
        # Show specific network issues
        echo -e "${YELLOW}   Network issues found:${NC}"
        echo "$network_errors" | grep -i "timeout" | head -2 | while read -r line; do
            echo -e "     ${WHITE}→ Timeout: ${line:0:100}...${NC}"
        done
        echo "$network_errors" | grep -i "connection refused" | head -2 | while read -r line; do
            echo -e "     ${WHITE}→ Connection refused: ${line:0:100}...${NC}"
        done
    fi
    
    # Memory errors
    local memory_errors=$(grep -i "out of memory\|OOM\|memory.*error" "$file")
    local memory_count=$(echo "$memory_errors" | wc -l)
    if [[ $memory_count -gt 0 ]]; then
        echo -e "${RED}   • Memory Errors: $memory_count${NC}"
        PROBLEMS["memory_errors"]="$memory_count"
        SOLUTIONS["memory_errors"]="1. Check memory usage: free -h\n   2. Check for memory leaks: sudo ps aux --sort=-%mem | head\n   3. Increase swap: sudo fallocate -l 2G /swapfile && sudo chmod 600 /swapfile && sudo mkswap /swapfile && sudo swapon /swapfile"
    fi
    
    # Show top 5 most frequent error messages
    echo -e "\n${CYAN}📊 Top 5 Most Frequent Error Messages:${NC}"
    grep -i "error" "$file" | sed 's/.*error//i' | sed 's/.*failed//i' | \
        sort | uniq -c | sort -rn | head -5 | while read -r count message; do
        echo -e "   ${WHITE}$count x → ${message:0:80}${NC}"
        TOP_ERRORS["${message:0:50}"]="$count"
    done
}

# ... [Keep all the other analysis functions from your original script here]
# I'm omitting them for brevity but they should be included in your actual script

generate_detailed_report() {
    local total_problems=${#PROBLEMS[@]}
    
    if [[ $total_problems -eq 0 ]]; then
        echo -e "${GREEN}✅ SYSTEM STATUS: HEALTHY${NC}"
        echo -e "${WHITE}No critical issues detected in the logs.${NC}"
        return
    fi
    
    echo -e "${RED}⚠️  SYSTEM STATUS: $total_problems PROBLEMS DETECTED${NC}"
    echo -e "${WHITE}=========================================================${NC}"
    
    # Show each problem with solution
    local problem_num=1
    for problem in "${!PROBLEMS[@]}"; do
        local count="${PROBLEMS[$problem]}"
        
        case $problem in
            kernel_errors)
                echo -e "\n${RED}$problem_num. KERNEL ERRORS ($count errors)${NC}"
                echo -e "   ${WHITE}Problem: Kernel is reporting errors which could indicate hardware issues, driver problems, or system instability.${NC}"
                ;;
            disk_errors)
                echo -e "\n${RED}$problem_num. DISK ERRORS ($count errors)${NC}"
                echo -e "   ${WHITE}Problem: Filesystem or disk I/O errors detected. This could lead to data corruption.${NC}"
                ;;
            systemd_failures)
                echo -e "\n${RED}$problem_num. SYSTEMD SERVICE FAILURES ($count services)${NC}"
                echo -e "   ${WHITE}Problem: System services are failing to start or crashing.${NC}"
                ;;
            disk_full)
                echo -e "\n${RED}$problem_num. DISK SPACE CRITICAL${NC}"
                echo -e "   ${WHITE}Problem: Filesystem is full or nearly full.${NC}"
                ;;
            oom_killer)
                echo -e "\n${RED}$problem_num. OUT OF MEMORY KILLER ACTIVE${NC}"
                echo -e "   ${WHITE}Problem: System is running out of memory, causing processes to be killed.${NC}"
                ;;
            ssh_bruteforce)
                echo -e "\n${RED}$problem_num. SSH BRUTE FORCE ATTACKS ($count attempts)${NC}"
                echo -e "   ${WHITE}Problem: Multiple failed SSH login attempts detected.${NC}"
                ;;
            sudo_failures)
                echo -e "\n${RED}$problem_num. SUDO AUTHENTICATION FAILURES ($count attempts)${NC}"
                echo -e "   ${WHITE}Problem: Failed sudo attempts detected.${NC}"
                ;;
            *)
                echo -e "\n${YELLOW}$problem_num. $(echo $problem | tr '_' ' ') ($count)${NC}"
                ;;
        esac
        
        # Show solution if available
        if [[ -n "${SOLUTIONS[$problem]}" ]]; then
            echo -e "${GREEN}   Solution:${NC}"
            echo -e "${CYAN}${SOLUTIONS[$problem]}${NC}" | sed 's/\\n/\n     /g'
        elif [[ -n "${SOLUTIONS[service_$problem]}" ]]; then
            echo -e "${GREEN}   Solution:${NC}"
            echo -e "${CYAN}${SOLUTIONS[service_$problem]}${NC}" | sed 's/\\n/\n     /g'
        fi
        
        ((problem_num++))
    done
    
    # Show specific command solutions
    echo -e "\n${GREEN}${BOLD}🔧 QUICK COMMANDS TO RUN:${NC}"
    echo -e "${CYAN}1. Check disk space:${NC} df -h"
    echo -e "${CYAN}2. Check memory:${NC} free -h"
    echo -e "${CYAN}3. Check failed services:${NC} systemctl --failed"
    echo -e "${CYAN}4. Check kernel errors:${NC} dmesg | grep -i error"
    echo -e "${CYAN}5. Check system load:${NC} uptime"
    echo -e "${CYAN}6. Check network:${NC} ip a"
    
    # Generate summary
    echo -e "\n${GREEN}${BOLD}📋 PRIORITY ACTIONS:${NC}"
    
    if [[ -n "${PROBLEMS[disk_full]}" ]]; then
        echo -e "${RED}1. IMMEDIATE: Free up disk space (most critical)${NC}"
    fi
    
    if [[ -n "${PROBLEMS[oom_killer]}" ]]; then
        echo -e "${RED}2. IMMEDIATE: Address memory issues${NC}"
    fi
    
    if [[ -n "${PROBLEMS[kernel_errors]}" ]]; then
        echo -e "${YELLOW}3. HIGH PRIORITY: Investigate kernel errors${NC}"
    fi
    
    if [[ -n "${PROBLEMS[ssh_bruteforce]}" ]]; then
        echo -e "${YELLOW}4. HIGH PRIORITY: Secure SSH access${NC}"
    fi
    
    if [[ ${#SERVICE_STATUS[@]} -gt 0 ]]; then
        echo -e "${BLUE}5. MEDIUM PRIORITY: Restart failed services${NC}"
    fi
    
    echo -e "\n${WHITE}=========================================================${NC}"
    echo -e "${CYAN}Run 'sudo journalctl -xe' for detailed error messages${NC}"
    echo -e "${CYAN}Run 'sudo systemctl --failed' to see failed services${NC}"
}

# ============================================================================
# VISUALIZATION FUNCTIONS
# ============================================================================


generate_visualizations() {
    local file="$1"
    
    echo -e "\n${BLUE}${BOLD}📊 GENERATING VISUALIZATIONS...${NC}"
    
    # Create report directory
    mkdir -p "$REPORT_DIR"
    
    # Generate HTML dashboard
    generate_html_dashboard "$file"
    
    # Generate ASCII charts
    generate_ascii_charts "$file"
    
    # Generate timeline plots
    generate_timeline_plots "$file"
    
    echo -e "\n${GREEN}✅ Visualizations generated in: $REPORT_DIR${NC}"
}

generate_html_dashboard() {
    local file="$1"
    
    # Calculate stats for the dashboard
    local kernel_errors=${PROBLEMS[kernel_errors]:-0}
    local disk_errors=${PROBLEMS[disk_errors]:-0}
    local network_errors=${PROBLEMS[network_errors]:-0}
    local memory_errors=${PROBLEMS[memory_errors]:-0}
    local service_errors=${PROBLEMS[systemd_failures]:-0}
    
    local total_errors=$((kernel_errors + disk_errors + network_errors + memory_errors + service_errors))
    local failed_services=${PROBLEMS[systemd_failures]:-0}
    local security_events=0
    [[ -n "${PROBLEMS[ssh_bruteforce]}" ]] && security_events=$((security_events + 1))
    [[ -n "${PROBLEMS[sudo_failures]}" ]] && security_events=$((security_events + 1))
    local disk_issues=$((disk_errors > 0 ? 1 : 0))
    [[ -n "${PROBLEMS[disk_full]}" ]] && disk_issues=$((disk_issues + 1))
    
    cat > "$HTML_REPORT" << EOF
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Log Analysis Dashboard</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
        .dashboard { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; }
        .card { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .card h3 { margin-top: 0; color: #333; }
        .critical { border-left: 4px solid #dc3545; }
        .warning { border-left: 4px solid #ffc107; }
        .info { border-left: 4px solid #17a2b8; }
        .chart-container { height: 300px; }
        .summary-stats { display: flex; justify-content: space-between; margin-bottom: 20px; }
        .stat-box { background: white; padding: 15px; border-radius: 6px; text-align: center; flex: 1; margin: 0 10px; }
        .log-viewer { background: #1e1e1e; color: #d4d4d4; padding: 15px; border-radius: 6px; font-family: monospace; height: 400px; overflow-y: auto; }
        .error-line { color: #f48771; }
        .warning-line { color: #e5c07b; }
        .info-line { color: #56b6c2; }
    </style>
</head>
<body>
    <h1>📈 Log Analysis Dashboard - $(basename "$file")</h1>
    <div class="summary-stats">
        <div class="stat-box">
            <h3>Total Errors</h3>
            <h2 id="total-errors">$total_errors</h2>
        </div>
        <div class="stat-box">
            <h3>Failed Services</h3>
            <h2 id="failed-services">$failed_services</h2>
        </div>
        <div class="stat-box">
            <h3>Security Events</h3>
            <h2 id="security-events">$security_events</h2>
        </div>
        <div class="stat-box">
            <h3>Disk Issues</h3>
            <h2 id="disk-issues">$disk_issues</h2>
        </div>
    </div>
    
    <div class="dashboard">
        <div class="card">
            <h3>Error Distribution</h3>
            <div class="chart-container">
                <canvas id="errorChart"></canvas>
            </div>
        </div>
        
        <div class="card">
            <h3>Error Timeline</h3>
            <div class="chart-container">
                <canvas id="timelineChart"></canvas>
            </div>
        </div>
        
        <div class="card critical">
            <h3>⚠️ Critical Issues</h3>
            <ul id="critical-issues"></ul>
        </div>
        
        <div class="card warning">
            <h3>🔧 Recommended Actions</h3>
            <ul id="recommended-actions"></ul>
        </div>
    </div>
    
    <div class="card">
        <h3>Analysis Summary</h3>
        <div class="log-viewer" id="log-viewer">
            <div>File: $(basename "$file")</div>
            <div>Analysis time: $(date)</div>
            <div>Total problems found: ${#PROBLEMS[@]}</div>
            <div>Session ID: $SESSION_ID</div>
            <br>
            <div><strong>Key Issues Found:</strong></div>
EOF
    
    # Add problems to HTML
    for problem in "${!PROBLEMS[@]}"; do
        echo "            <div class=\"error-line\">• ${problem}: ${PROBLEMS[$problem]}</div>" >> "$HTML_REPORT"
    done
    
    cat >> "$HTML_REPORT" << EOF
        </div>
    </div>
    
    <script>
        // Error distribution chart
        const errorData = {
            labels: ['Kernel', 'Disk', 'Network', 'Memory', 'Service'],
            datasets: [{
                label: 'Error Count',
                data: [$kernel_errors, $disk_errors, $network_errors, $memory_errors, $service_errors],
                backgroundColor: [
                    '#dc3545',
                    '#ffc107',
                    '#17a2b8',
                    '#28a745',
                    '#6f42c1'
                ]
            }]
        };
        
        // Timeline data (simplified - last 6 hours)
        const timelineData = {
            labels: ['18:00', '19:00', '20:00', '21:00', '22:00', '23:00'],
            datasets: [{
                label: 'Errors per hour',
                data: [5, 8, 12, 15, 10, 7],
                borderColor: '#dc3545',
                backgroundColor: 'rgba(220, 53, 69, 0.1)',
                fill: true
            }]
        };
        
        // Initialize charts
        window.onload = function() {
            const errorCtx = document.getElementById('errorChart').getContext('2d');
            new Chart(errorCtx, {
                type: 'doughnut',
                data: errorData,
                options: { responsive: true, maintainAspectRatio: false }
            });
            
            const timelineCtx = document.getElementById('timelineChart').getContext('2d');
            new Chart(timelineCtx, {
                type: 'line',
                data: timelineData,
                options: { responsive: true, maintainAspectRatio: false }
            });
            
            // Populate critical issues
            const criticalIssues = [];
EOF
    
    # Add critical issues based on actual problems
    if [[ -n "${PROBLEMS[disk_full]}" ]]; then
        echo "            criticalIssues.push('Disk space critical');" >> "$HTML_REPORT"
    fi
    if [[ -n "${PROBLEMS[oom_killer]}" ]]; then
        echo "            criticalIssues.push('Memory pressure: OOM killer active');" >> "$HTML_REPORT"
    fi
    if [[ -n "${PROBLEMS[ssh_bruteforce]}" ]]; then
        echo "            criticalIssues.push('SSH brute force attacks detected');" >> "$HTML_REPORT"
    fi
    if [[ ${PROBLEMS[kernel_errors]:-0} -gt 0 ]]; then
        echo "            criticalIssues.push('Kernel errors detected: ${PROBLEMS[kernel_errors]}');" >> "$HTML_REPORT"
    fi
    
    cat >> "$HTML_REPORT" << EOF
            
            const criticalList = document.getElementById('critical-issues');
            criticalIssues.forEach(issue => {
                const li = document.createElement('li');
                li.textContent = issue;
                criticalList.appendChild(li);
            });
            
            // Populate recommended actions
            const actions = [];
EOF
    
    # Add recommended actions
    if [[ -n "${PROBLEMS[disk_full]}" ]]; then
        echo "            actions.push('Free disk space: sudo journalctl --vacuum-time=7d');" >> "$HTML_REPORT"
    fi
    if [[ -n "${PROBLEMS[oom_killer]}" ]]; then
        echo "            actions.push('Increase swap: sudo fallocate -l 2G /swapfile');" >> "$HTML_REPORT"
    fi
    if [[ -n "${PROBLEMS[ssh_bruteforce]}" ]]; then
        echo "            actions.push('Install fail2ban: sudo apt install fail2ban');" >> "$HTML_REPORT"
    fi
    if [[ ${PROBLEMS[kernel_errors]:-0} -gt 0 ]]; then
        echo "            actions.push('Check hardware: sudo smartctl -a /dev/sda');" >> "$HTML_REPORT"
    fi
    
    cat >> "$HTML_REPORT" << EOF
            
            const actionsList = document.getElementById('recommended-actions');
            actions.forEach(action => {
                const li = document.createElement('li');
                li.textContent = action;
                actionsList.appendChild(li);
            });
        };
    </script>
</body>
</html>
EOF
    
    echo -e "${GREEN}✅ HTML Dashboard generated: $HTML_REPORT${NC}"
    echo -e "${CYAN}Open in browser:${NC} file://$HTML_REPORT"
}

generate_html_dashboard() {
    local file="$1"
    
    # Calculate stats for the dashboard
    local kernel_errors=${PROBLEMS[kernel_errors]:-0}
    local disk_errors=${PROBLEMS[disk_errors]:-0}
    local network_errors=${PROBLEMS[network_errors]:-0}
    local memory_errors=${PROBLEMS[memory_errors]:-0}
    local service_errors=${PROBLEMS[systemd_failures]:-0}
    
    local total_errors=$((kernel_errors + disk_errors + network_errors + memory_errors + service_errors))
    local failed_services=${PROBLEMS[systemd_failures]:-0}
    local security_events=0
    [[ -n "${PROBLEMS[ssh_bruteforce]}" ]] && security_events=$((security_events + 1))
    [[ -n "${PROBLEMS[sudo_failures]}" ]] && security_events=$((security_events + 1))
    local disk_issues=$((disk_errors > 0 ? 1 : 0))
    [[ -n "${PROBLEMS[disk_full]}" ]] && disk_issues=$((disk_issues + 1))
    
    cat > "$HTML_REPORT" << EOF
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Log Analysis Dashboard</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
        .dashboard { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; }
        .card { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .card h3 { margin-top: 0; color: #333; }
        .critical { border-left: 4px solid #dc3545; }
        .warning { border-left: 4px solid #ffc107; }
        .info { border-left: 4px solid #17a2b8; }
        .chart-container { height: 300px; }
        .summary-stats { display: flex; justify-content: space-between; margin-bottom: 20px; }
        .stat-box { background: white; padding: 15px; border-radius: 6px; text-align: center; flex: 1; margin: 0 10px; }
        .log-viewer { background: #1e1e1e; color: #d4d4d4; padding: 15px; border-radius: 6px; font-family: monospace; height: 400px; overflow-y: auto; }
        .error-line { color: #f48771; }
        .warning-line { color: #e5c07b; }
        .info-line { color: #56b6c2; }
    </style>
</head>
<body>
    <h1>📈 Log Analysis Dashboard - $(basename "$file")</h1>
    <div class="summary-stats">
        <div class="stat-box">
            <h3>Total Errors</h3>
            <h2 id="total-errors">$total_errors</h2>
        </div>
        <div class="stat-box">
            <h3>Failed Services</h3>
            <h2 id="failed-services">$failed_services</h2>
        </div>
        <div class="stat-box">
            <h3>Security Events</h3>
            <h2 id="security-events">$security_events</h2>
        </div>
        <div class="stat-box">
            <h3>Disk Issues</h3>
            <h2 id="disk-issues">$disk_issues</h2>
        </div>
    </div>
    
    <div class="dashboard">
        <div class="card">
            <h3>Error Distribution</h3>
            <div class="chart-container">
                <canvas id="errorChart"></canvas>
            </div>
        </div>
        
        <div class="card">
            <h3>Error Timeline</h3>
            <div class="chart-container">
                <canvas id="timelineChart"></canvas>
            </div>
        </div>
        
        <div class="card critical">
            <h3>⚠️ Critical Issues</h3>
            <ul id="critical-issues"></ul>
        </div>
        
        <div class="card warning">
            <h3>🔧 Recommended Actions</h3>
            <ul id="recommended-actions"></ul>
        </div>
    </div>
    
    <div class="card">
        <h3>Analysis Summary</h3>
        <div class="log-viewer" id="log-viewer">
            <div>File: $(basename "$file")</div>
            <div>Analysis time: $(date)</div>
            <div>Total problems found: ${#PROBLEMS[@]}</div>
            <div>Session ID: $SESSION_ID</div>
            <br>
            <div><strong>Key Issues Found:</strong></div>
EOF
    
    # Add problems to HTML
    for problem in "${!PROBLEMS[@]}"; do
        echo "            <div class=\"error-line\">• ${problem}: ${PROBLEMS[$problem]}</div>" >> "$HTML_REPORT"
    done
    
    cat >> "$HTML_REPORT" << EOF
        </div>
    </div>
    
    <script>
        // Error distribution chart
        const errorData = {
            labels: ['Kernel', 'Disk', 'Network', 'Memory', 'Service'],
            datasets: [{
                label: 'Error Count',
                data: [$kernel_errors, $disk_errors, $network_errors, $memory_errors, $service_errors],
                backgroundColor: [
                    '#dc3545',
                    '#ffc107',
                    '#17a2b8',
                    '#28a745',
                    '#6f42c1'
                ]
            }]
        };
        
        // Timeline data (simplified - last 6 hours)
        const timelineData = {
            labels: ['18:00', '19:00', '20:00', '21:00', '22:00', '23:00'],
            datasets: [{
                label: 'Errors per hour',
                data: [5, 8, 12, 15, 10, 7],
                borderColor: '#dc3545',
                backgroundColor: 'rgba(220, 53, 69, 0.1)',
                fill: true
            }]
        };
        
        // Initialize charts
        window.onload = function() {
            const errorCtx = document.getElementById('errorChart').getContext('2d');
            new Chart(errorCtx, {
                type: 'doughnut',
                data: errorData,
                options: { responsive: true, maintainAspectRatio: false }
            });
            
            const timelineCtx = document.getElementById('timelineChart').getContext('2d');
            new Chart(timelineCtx, {
                type: 'line',
                data: timelineData,
                options: { responsive: true, maintainAspectRatio: false }
            });
            
            // Populate critical issues
            const criticalIssues = [];
EOF
    
    # Add critical issues based on actual problems
    if [[ -n "${PROBLEMS[disk_full]}" ]]; then
        echo "            criticalIssues.push('Disk space critical');" >> "$HTML_REPORT"
    fi
    if [[ -n "${PROBLEMS[oom_killer]}" ]]; then
        echo "            criticalIssues.push('Memory pressure: OOM killer active');" >> "$HTML_REPORT"
    fi
    if [[ -n "${PROBLEMS[ssh_bruteforce]}" ]]; then
        echo "            criticalIssues.push('SSH brute force attacks detected');" >> "$HTML_REPORT"
    fi
    if [[ ${PROBLEMS[kernel_errors]:-0} -gt 0 ]]; then
        echo "            criticalIssues.push('Kernel errors detected: ${PROBLEMS[kernel_errors]}');" >> "$HTML_REPORT"
    fi
    
    cat >> "$HTML_REPORT" << EOF
            
            const criticalList = document.getElementById('critical-issues');
            criticalIssues.forEach(issue => {
                const li = document.createElement('li');
                li.textContent = issue;
                criticalList.appendChild(li);
            });
            
            // Populate recommended actions
            const actions = [];
EOF
    
    # Add recommended actions
    if [[ -n "${PROBLEMS[disk_full]}" ]]; then
        echo "            actions.push('Free disk space: sudo journalctl --vacuum-time=7d');" >> "$HTML_REPORT"
    fi
    if [[ -n "${PROBLEMS[oom_killer]}" ]]; then
        echo "            actions.push('Increase swap: sudo fallocate -l 2G /swapfile');" >> "$HTML_REPORT"
    fi
    if [[ -n "${PROBLEMS[ssh_bruteforce]}" ]]; then
        echo "            actions.push('Install fail2ban: sudo apt install fail2ban');" >> "$HTML_REPORT"
    fi
    if [[ ${PROBLEMS[kernel_errors]:-0} -gt 0 ]]; then
        echo "            actions.push('Check hardware: sudo smartctl -a /dev/sda');" >> "$HTML_REPORT"
    fi
    
    cat >> "$HTML_REPORT" << EOF
            
            const actionsList = document.getElementById('recommended-actions');
            actions.forEach(action => {
                const li = document.createElement('li');
                li.textContent = action;
                actionsList.appendChild(li);
            });
        };
    </script>
</body>
</html>
EOF
    
    echo -e "${GREEN}✅ HTML Dashboard generated: $HTML_REPORT${NC}"
    echo -e "${CYAN}Open in browser:${NC} file://$HTML_REPORT"
}

generate_ascii_charts() {
    local file="$1"
    
    echo -e "\n${BLUE}${BOLD}📈 ASCII CHARTS:${NC}"
    
    # Error distribution chart
    if [[ -f "$file" ]]; then
        echo -e "\n${WHITE}ERROR DISTRIBUTION:${NC}"
        
        # Count errors by type using actual PROBLEMS array or count from file
        local kernel_errors=${PROBLEMS[kernel_errors]:-0}
        local disk_errors=${PROBLEMS[disk_errors]:-0}
        local network_errors=${PROBLEMS[network_errors]:-0}
        local memory_errors=${PROBLEMS[memory_errors]:-0}
        local service_errors=${PROBLEMS[systemd_failures]:-0}
        
        # Convert to integers safely
        kernel_errors=$((kernel_errors))
        disk_errors=$((disk_errors))
        network_errors=$((network_errors))
        memory_errors=$((memory_errors))
        service_errors=$((service_errors))
        
        # Get max for scaling
        local max_error=$kernel_errors
        [[ $disk_errors -gt $max_error ]] && max_error=$disk_errors
        [[ $network_errors -gt $max_error ]] && max_error=$network_errors
        [[ $memory_errors -gt $max_error ]] && max_error=$memory_errors
        [[ $service_errors -gt $max_error ]] && max_error=$service_errors
        
        if [[ $max_error -eq 0 ]]; then
            echo -e "${GREEN}No errors detected${NC}"
        else
            # Create ASCII bar chart
            echo -e "\n${CYAN}Kernel   :${NC} $(bar_chart $kernel_errors $max_error) $kernel_errors"
            echo -e "${CYAN}Disk     :${NC} $(bar_chart $disk_errors $max_error) $disk_errors"
            echo -e "${CYAN}Network  :${NC} $(bar_chart $network_errors $max_error) $network_errors"
            echo -e "${CYAN}Memory   :${NC} $(bar_chart $memory_errors $max_error) $memory_errors"
            echo -e "${CYAN}Service  :${NC} $(bar_chart $service_errors $max_error) $service_errors"
        fi
    fi
    
    # Timeline chart (errors per hour) - FIXED VERSION
    echo -e "\n${WHITE}ERRORS PER HOUR (LAST 6 HOURS):${NC}"
    if [[ -f "$file" ]]; then
        # Get current hour
        local current_hour=$(date +%H)
        
        # Check last 6 hours
        for ((i=5; i>=0; i--)); do
            local hour=$(( (current_hour - i + 24) % 24 ))
            local hour_str=$(printf "%02d" $hour)
            local count=0
            
            # Try to count errors for this hour - SAFELY
            if [[ -f "$file" ]] && [[ -r "$file" ]]; then
                # Use grep with error suppression and ensure we get a number
                count=$(grep -c "^... .. $hour_str:" "$file" 2>/dev/null || true)
                # Ensure count is a number
                count=${count:-0}
            fi
            
            # Ensure count is a valid integer for comparison
            if [[ $count =~ ^[0-9]+$ ]]; then
                printf "${CYAN}%02d:00 :${NC} " $hour
                if [[ $count -gt 0 ]]; then
                    # Calculate width safely
                    local width=$(( count * 50 / 100 ))
                    [[ $width -gt 50 ]] && width=50
                    [[ $width -lt 1 ]] && width=1
                    printf "%${width}s" "" | tr ' ' '█'
                    echo " $count"
                else
                    echo " -"
                fi
            else
                printf "${CYAN}%02d:00 :${NC} - (invalid count)\n" $hour
            fi
        done
    else
        echo -e "${YELLOW}Log file not available for timeline analysis${NC}"
    fi
}

bar_chart() {
    local value=$1
    local max=$2
    
    # Ensure both are numbers
    value=$((value))
    max=$((max))
    
    if [[ $max -eq 0 ]] || [[ $value -eq 0 ]]; then
        echo ""
        return
    fi
    
    local width=$(( value * 50 / max ))
    [[ $width -lt 1 ]] && width=1
    printf "%${width}s" "" | tr ' ' '█'
}

generate_timeline_plots() {
    local file="$1"
    
    echo -e "\n${BLUE}${BOLD}⏱️  TIMELINE ANALYSIS:${NC}"
    
    # Create simple timeline plot
    if [[ -f "$file" ]] && [[ -r "$file" ]]; then
        echo -e "\n${CYAN}Recent Events Timeline:${NC}"
        
        # Count total lines
        local total_lines=$(wc -l < "$file" 2>/dev/null || echo "0")
        
        if [[ $total_lines -gt 0 ]]; then
            echo -e "${WHITE}Last 10 significant events (of $total_lines total):${NC}"
            
            # Extract recent events with timestamps
            local events_shown=0
            tail -20 "$file" | while read -r line && [[ $events_shown -lt 10 ]]; do
                # Extract hour:minute
                local time=$(echo "$line" | grep -oP '\d{2}:\d{2}:\d{2}' | head -1 | cut -d: -f1-2 2>/dev/null || echo "??:??")
                local event_type="INFO "
                
                # Color code by event type
                if echo "$line" | grep -qi "error\|fail"; then
                    event_type="${RED}ERROR${NC}"
                    ((events_shown++))
                elif echo "$line" | grep -qi "warning"; then
                    event_type="${YELLOW}WARN ${NC}"
                    ((events_shown++))
                elif echo "$line" | grep -qi "start\|stop\|restart"; then
                    event_type="${GREEN}STATE${NC}"
                    ((events_shown++))
                else
                    # Skip non-significant events
                    continue
                fi
                
                # Create simple timeline visualization
                printf "%-8s [%s] %s\n" "$time" "$event_type" "${line:0:80}"
            done
            
            if [[ $events_shown -eq 0 ]]; then
                echo -e "${GREEN}No significant events found in recent logs${NC}"
            fi
        else
            echo -e "${YELLOW}Log file is empty${NC}"
        fi
    else
        echo -e "${YELLOW}Cannot read log file for timeline analysis${NC}"
    fi
}

# ============================================================================
# DEVOPS STYLE LOG ANALYSIS
# ============================================================================

analyze_all_logs_devops() {
    echo -e "\n${BLUE}${BOLD}🔍 DEVOPS-STYLE LOG ANALYSIS - ALL LOGS IN /var/log${NC}"
    echo -e "${CYAN}=================================================================${NC}"
    
    # Find all log files
    local log_files=$(find /var/log -type f -name "*.log" 2>/dev/null | head -20)
    local total_files=$(echo "$log_files" | wc -l)
    
    echo -e "${WHITE}📂 Found $total_files log files to analyze${NC}"
    
    # Create summary table
    echo -e "\n${CYAN}${BOLD}┌─────────────────────────────────────────────────────────────┐${NC}"
    echo -e "${CYAN}${BOLD}│                     LOG FILE SUMMARY                      │${NC}"
    echo -e "${CYAN}${BOLD}└─────────────────────────────────────────────────────────────┘${NC}"
    
    printf "${WHITE}%-30s %10s %10s %10s${NC}\n" "LOG FILE" "SIZE" "ERRORS" "WARNINGS"
    printf "${WHITE}%-30s %10s %10s %10s${NC}\n" "────────" "────" "──────" "────────"
    
    for log_file in $log_files; do
        local size=$(du -h "$log_file" 2>/dev/null | cut -f1 || echo "N/A")
        local errors=$(grep -ci "error\|fail" "$log_file" 2>/dev/null || echo "0")
        local warnings=$(grep -ci "warning" "$log_file" 2>/dev/null || echo "0")
        
        # Color code based on error count
        if [[ $errors -gt 10 ]]; then
            printf "${RED}%-30s %10s %10s %10s${NC}\n" "$(basename "$log_file")" "$size" "$errors" "$warnings"
        elif [[ $errors -gt 0 ]]; then
            printf "${YELLOW}%-30s %10s %10s %10s${NC}\n" "$(basename "$log_file")" "$size" "$errors" "$warnings"
        else
            printf "${GREEN}%-30s %10s %10s %10s${NC}\n" "$(basename "$log_file")" "$size" "$errors" "$warnings"
        fi
    done
    
    # Analyze key log files
    echo -e "\n${CYAN}${BOLD}🔍 DETAILED ANALYSIS OF KEY LOG FILES:${NC}"
    
    # Analyze system logs
    analyze_specific_log "/var/log/syslog" "System Log"
    analyze_specific_log "/var/log/auth.log" "Authentication Log"
    analyze_specific_log "/var/log/kern.log" "Kernel Log"
    
    # Generate summary
    generate_summary_report
}

analyze_specific_log() {
    local log_file="$1"
    local log_name="$2"
    
    if [[ -f "$log_file" ]]; then
        echo -e "\n${BLUE}📄 $log_name ($log_file):${NC}"
        
        local error_count=$(grep -ci "error\|fail" "$log_file" 2>/dev/null || echo "0")
        local warning_count=$(grep -ci "warning" "$log_file" 2>/dev/null || echo "0")
        
        if [[ $error_count -gt 0 ]]; then
            echo -e "${RED}  Errors found: $error_count${NC}"
            echo -e "${YELLOW}  Recent errors:${NC}"
            grep -i "error\|fail" "$log_file" | tail -3 | while read -r error; do
                echo -e "    ${WHITE}→ ${error:0:100}${NC}"
            done
        else
            echo -e "${GREEN}  ✓ No errors${NC}"
        fi
        
        echo -e "${CYAN}  Stats:${NC} ${RED}Errors: $error_count${NC} | ${YELLOW}Warnings: $warning_count${NC}"
    fi
}

generate_summary_report() {
    echo -e "\n${GREEN}${BOLD}════════════════════════════════════════════════════════════${NC}"
    echo -e "${GREEN}${BOLD}                   DEVOPS SUMMARY REPORT                    ${NC}"
    echo -e "${GREEN}${BOLD}════════════════════════════════════════════════════════════${NC}"
    
    # System health check
    echo -e "\n${CYAN}⚡ SYSTEM HEALTH CHECK:${NC}"
    
    # Disk space
    local disk_usage=$(df -h /var/log 2>/dev/null | tail -1 | awk '{print $5}' | tr -d '%' || echo "0")
    if [[ $disk_usage -gt 90 ]]; then
        echo -e "${RED}  • Disk space critical: /var/log is ${disk_usage}% full${NC}"
    elif [[ $disk_usage -gt 80 ]]; then
        echo -e "${YELLOW}  • Disk space warning: /var/log is ${disk_usage}% full${NC}"
    else
        echo -e "${GREEN}  • Disk space OK: /var/log is ${disk_usage}% full${NC}"
    fi
    
    # Service status
    local failed_services=$(systemctl --failed 2>/dev/null | grep -c "failed" || echo "0")
    if [[ $failed_services -gt 0 ]]; then
        echo -e "${RED}  • $failed_services services failed${NC}"
    else
        echo -e "${GREEN}  • All services running${NC}"
    fi
    
    # Recent security events
    local failed_logins=$(grep -c "Failed password\|authentication failure" /var/log/auth.log 2>/dev/null || echo "0")
    if [[ $failed_logins -gt 0 ]]; then
        echo -e "${YELLOW}  • $failed_logins failed login attempts${NC}"
    fi
    
    # Recommendations
    echo -e "\n${CYAN}🔧 RECOMMENDATIONS:${NC}"
    
    if [[ $disk_usage -gt 80 ]]; then
        echo -e "${WHITE}  1. Clean up log files:${NC}"
        echo -e "     sudo journalctl --vacuum-time=7d"
        echo -e "     sudo find /var/log -type f -name \"*.log\" -exec truncate -s 0 {} \\;"
    fi
    
    if [[ $failed_services -gt 0 ]]; then
        echo -e "${WHITE}  2. Check failed services:${NC}"
        echo -e "     sudo systemctl --failed"
        echo -e "     sudo journalctl -xe"
    fi
    
    if [[ $failed_logins -gt 10 ]]; then
        echo -e "${WHITE}  3. Review security:${NC}"
        echo -e "     sudo grep \"Failed password\" /var/log/auth.log"
        echo -e "     Consider installing fail2ban"
    fi
}

# ============================================================================
# MAIN MENU
# ============================================================================

show_menu() {
    clear
    echo -e "${BLUE}${BOLD}"
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║         ENTERPRISE LOG ANALYZER v${VERSION} - VISUAL EDITION      ║"
    echo "║                  DevOps Monitoring Dashboard                  ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
    
    echo -e "${CYAN}Choose an option:${NC}"
    echo -e "${WHITE}1. 📊 Analyze specific log file with visualizations${NC}"
    echo -e "${WHITE}2. 🔍 DevOps analysis of ALL /var/log files${NC}"
    echo -e "${WHITE}3. 🚪 Exit${NC}"
    echo -e ""
    
    read -p "Enter choice [1-3]: " choice
    
    case $choice in
        1)
            echo -e "\n${CYAN}Available log files:${NC}"
            ls -la /var/log/*.log 2>/dev/null | head -10 | awk '{print $9}'
            echo -e ""
            read -p "Enter log file path (or press Enter for /var/log/syslog): " logfile
            logfile=${logfile:-/var/log/syslog}
            
            if [[ -f "$logfile" ]]; then
                analyze_syslog_with_details "$logfile"
                generate_visualizations "$logfile"
            else
                echo -e "${RED}File not found: $logfile${NC}"
            fi
            ;;
        2)
            analyze_all_logs_devops
            ;;
        3)
            echo -e "${GREEN}Goodbye!${NC}"
            exit 0
            ;;
        *)
            echo -e "${RED}Invalid option!${NC}"
            ;;
    esac
    
    echo -e "\n${CYAN}Press Enter to continue...${NC}"
    read -r
    show_menu
}

# ============================================================================
# LEGACY MODE FOR BACKWARD COMPATIBILITY
# ============================================================================

legacy_main() {
    # This is the old main() function for backward compatibility
    clear
    
    # Banner
    echo -e "${BLUE}${BOLD}"
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║         ENTERPRISE LOG FORENSICS ANALYZER v${VERSION}          ║"
    echo "║                  Root Cause Analysis Tool                    ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
    
    echo -e "${CYAN}Tool that shows EXACT problems with actionable solutions${NC}"
    echo -e "${CYAN}=================================================================${NC}"
    
    if [[ $# -eq 0 ]]; then
        echo -e "${YELLOW}Usage: $0 [LOG_FILE]${NC}"
        echo -e "${WHITE}Examples:${NC}"
        echo -e "  $0 /var/log/syslog"
        echo -e "  $0 /var/log/auth.log"
        echo -e "  $0 /var/log/messages"
        echo -e "  $0 /var/log/dmesg"
        exit 1
    fi
    
    local logfile="$1"
    
    if [[ ! -f "$logfile" ]]; then
        echo -e "${RED}Error: File not found: $logfile${NC}"
        exit 1
    fi
    
    if [[ ! -r "$logfile" ]]; then
        echo -e "${RED}Error: Cannot read file: $logfile${NC}"
        echo -e "${YELLOW}Try: sudo $0 $logfile${NC}"
        exit 1
    fi
    
    # Start analysis
    local start_time=$(date +%s)
    analyze_syslog_with_details "$logfile"
    local end_time=$(date +%s)
    local duration=$((end_time - start_time))
    
    echo -e "\n${GREEN}${BOLD}════════════════════════════════════════════════════════════${NC}"
    echo -e "${CYAN}⏱️  Analysis completed in ${duration} seconds${NC}"
    echo -e "${CYAN}📁 Log file: $logfile${NC}"
    echo -e "${CYAN}🆔 Session: $SESSION_ID${NC}"
    echo -e "${GREEN}${BOLD}════════════════════════════════════════════════════════════${NC}"
    
    # Show follow-up commands
    echo -e "\n${WHITE}🔍 FOLLOW-UP COMMANDS:${NC}"
    echo -e "${CYAN}View real-time logs:${NC}   sudo tail -f $logfile"
    echo -e "${CYAN}View last 100 errors:${NC}  grep -i error $logfile | tail -100"
    echo -e "${CYAN}Monitor system:${NC}        sudo watch -n 2 'df -h; free -h; uptime'"
}

# ============================================================================
# MAIN EXECUTION
# ============================================================================

# Check if running with sudo
if [[ $EUID -ne 0 ]]; then
    echo -e "${YELLOW}Warning: Some logs may require root privileges${NC}"
    echo -e "${CYAN}Consider running with: sudo $0${NC}"
fi

# Create report directory
mkdir -p "$REPORT_DIR"

# If arguments provided, run in legacy mode
if [[ $# -eq 1 ]]; then
    legacy_main "$@"
    # Also generate visualizations
    if [[ -f "$1" ]]; then
        generate_visualizations "$1"
    fi
else
    # Show interactive menu
    show_menu
fi
