#!/bin/bash

# ============================================================================
# LIVE LOG ANALYZER PRO v9.0 - Smooth Terminal Dashboard (Like htop/btop)
# Professional log monitoring with seamless refresh
# ============================================================================

VERSION="9.0.0"
CONFIG_FILE="/etc/live-log-analyzer.conf"
DEFAULT_PATHS=("/var/log/syslog" "/var/log/auth.log" "/var/log/kern.log")
MONITORED_DIRS=("/var/log")
MONITOR_FILES=()
CUSTOM_PATHS=()
ALERT_THRESHOLD=10
ALERT_FILE="/tmp/live_alerts_$(date +%s).log"
REPORT_DIR="/tmp/live_log_analysis"
LIVE_DB="${REPORT_DIR}/live_metrics.db"

# ANSI Colors & UI Elements
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'
BOLD='\033[1m'
DIM='\033[2m'
BLINK='\033[5m'
REVERSE='\033[7m'
UNDERLINE='\033[4m'
SAVE_CURSOR='\033[s'
RESTORE_CURSOR='\033[u'
CLEAR_LINE='\033[2K'
MOVE_UP='\033[1A'
HIDE_CURSOR='\033[?25l'
SHOW_CURSOR='\033[?25h'

# Additional color definitions for gradients
GREEN_YELLOW='\033[0;33m'
ORANGE='\033[0;33m'
LIGHT_RED='\033[1;31m'

# Dashboard configuration
REFRESH_RATE=1
ERROR_THRESHOLD=10
OUTPUT_MODE="interactive"

# Security variables
declare -a DANGEROUS_PATTERNS=(
    '[;&|`$]'
    '(SELECT.*FROM|INSERT.*INTO|DELETE.*FROM|UPDATE.*SET)'
    '(\.\.\/|\.\.\\)'
)

# PII and Secret patterns for sanitization
declare -a PII_PATTERNS=(
    '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}'
    '\+?1?[-.]?\(?[0-9]{3}\)?[-.]?[0-9]{3}[-.]?[0-9]{4}'
    '\b[0-9]{4}[- ]?[0-9]{4}[- ]?[0-9]{4}[- ]?[0-9]{4}\b'
    '\b[0-9]{3}-[0-9]{2}-[0-9]{4}\b'
)

declare -a SECRET_PATTERNS=(
    '(api[_-]?key|token|secret|password|bearer)[[:space:]]*[:=][[:space:]]*['"'"'"]?[A-Za-z0-9+/=]+['"'"'"]?'
    'eyJ[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*'
    'AKIA[0-9A-Z]{16}'
)

declare -a CRITICAL_PATTERNS=(
    'password|passwd|pwd'
    'secret|token|api[_-]?key'
)

declare -A RATE_LIMIT_COUNTER
MAX_LINES_PER_SECOND=10000

# Dashboard state
declare -A ERROR_COUNTS
declare -A WARNING_COUNTS
CURRENT_MINUTE=$(date +"%Y%m%d%H%M")
LAST_MINUTE=0
ALERT_TRIGGERED=0

# Terminal dimensions
TERM_HEIGHT=0
TERM_WIDTH=0
DASHBOARD_START_LINE=0

# Cache for dashboard content
DASHBOARD_CACHE=()
LAST_ERROR_COUNT=0
LAST_WARNING_COUNT=0
LAST_SECURITY_COUNT=0
LAST_ALERT_COUNT=0

# Sanitization metrics
declare -i TOTAL_LINES_PROCESSED=0
declare -i TOTAL_BYTES_PROCESSED=0
declare -i PATTERNS_APPLIED=0
declare -i PATTERN_FAILURES=0
declare -i TRUNCATED_LINES_COUNT=0
declare -i OUTPUT_TRUNCATED_COUNT=0
declare -i VALIDATION_FAILURES=0

# ============================================================================
# CONFIGURATION MANAGEMENT
# ============================================================================

create_default_config() {
    cat > "$CONFIG_FILE" << 'EOF'
MONITOR_DIRS=("/var/log")
MONITOR_FILES=("/var/log/syslog" "/var/log/auth.log" "/var/log/kern.log")
CUSTOM_PATHS=()
ERROR_THRESHOLD=10
FOLLOW_NEW_FILES=true
SHOW_TIMESTAMPS=true
COLORIZE_OUTPUT=true
OUTPUT_MODE="interactive"
LOG_TO_FILE=true
HTML_REPORT=true
EOF
    echo -e "${GREEN}✅ Default configuration created: $CONFIG_FILE${NC}"
}

load_config() {
    if [[ -f "$CONFIG_FILE" ]]; then
        source "$CONFIG_FILE"
        # Reassign arrays after sourcing
        MONITORED_DIRS=("${MONITOR_DIRS[@]}")
        MONITOR_FILES=("${MONITOR_FILES[@]}")
        CUSTOM_PATHS=("${CUSTOM_PATHS[@]}")
    else
        create_default_config
        source "$CONFIG_FILE"
        MONITORED_DIRS=("${MONITOR_DIRS[@]}")
        MONITOR_FILES=("${MONITOR_FILES[@]}")
        CUSTOM_PATHS=("${CUSTOM_PATHS[@]}")
    fi
}

# ============================================================================
# TERMINAL CONTROL FUNCTIONS
# ============================================================================

get_terminal_size() {
    TERM_WIDTH=$(tput cols 2>/dev/null || echo 120)
    TERM_HEIGHT=$(tput lines 2>/dev/null || echo 30)
}

init_terminal() {
    get_terminal_size
    
    # Hide cursor and save terminal state
    printf "$HIDE_CURSOR"
    printf "\033[?1049h"  # Alternative screen buffer (like htop)
    
    # Trap exit to restore terminal
    trap restore_terminal EXIT INT TERM
}

restore_terminal() {
    printf "$SHOW_CURSOR"
    printf "\033[?1049l"  # Exit alternative screen buffer
    printf "\033[0m"      # Reset all attributes
    printf "\033[2J\033[H" # Clear screen
    echo -e "${GREEN}✅ Dashboard closed. Report: ${REPORT_DIR}/live_report.html${NC}"
}

# ============================================================================
# DATABASE FUNCTIONS
# ============================================================================

init_database() {
    mkdir -p "$REPORT_DIR"
    
    sqlite3 "$LIVE_DB" << 'EOF' 2>/dev/null
CREATE TABLE IF NOT EXISTS metrics (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
    log_file TEXT,
    severity TEXT,
    message TEXT
);

CREATE TABLE IF NOT EXISTS alerts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
    severity TEXT,
    alert_type TEXT,
    message TEXT,
    acknowledged INTEGER DEFAULT 0
);

CREATE INDEX IF NOT EXISTS idx_metrics_timestamp ON metrics(timestamp);
CREATE INDEX IF NOT EXISTS idx_metrics_severity ON metrics(severity);

PRAGMA journal_mode=WAL;
EOF
}

# ============================================================================
# LOG FILE DISCOVERY
# ============================================================================

discover_log_files() {
    local -a all_files=()
    local -a discovered_files=()
    local max_files="${MAX_LOG_FILES:-500}"
    local max_depth="${MAX_SEARCH_DEPTH:-10}"
    local exclude_patterns=(
        "*.gz" "*.bz2" "*.xz" "*.zip"
        "*.old" "*.bak" "*.tmp"
        "*.lock" "*.pid"
        "core\\.[0-9]+" "*.crash"
    )
    
    # Discovery phase 1: Pattern-based search in monitored directories
    for dir in "${MONITORED_DIRS[@]}"; do
        if [[ ! -d "$dir" ]]; then
            echo "WARNING: Directory does not exist: $dir" >&2
            continue
        fi
        
        if [[ ! -r "$dir" ]]; then
            echo "WARNING: Directory not readable: $dir" >&2
            continue
        fi
        
        # Build find command with performance optimizations
        local find_cmd="find \"$dir\" -maxdepth $max_depth -type f"
        
        # Add file patterns
        find_cmd+=" \\( -name \"*.log\" -o -name \"*.log.[0-9]*\" -o -name \"syslog*\" -o -name \"auth.log*\" -o -name \"messages*\" -o -name \"secure*\" -o -name \"*.out\" -o -name \"*.err\" \\)"
        
        # Exclude patterns
        for pattern in "${exclude_patterns[@]}"; do
            find_cmd+=" ! -name \"$pattern\""
        done
        
        # Add permission and follow symlinks (optional)
        find_cmd+=" -readable"
        [[ "${FOLLOW_SYMLINKS:-false}" == "true" ]] && find_cmd+=" -follow"
        
        # Execute find with timeout and limit
        local temp_files=()
        while IFS= read -r file; do
            temp_files+=("$file")
            
            # Early exit if we hit the limit
            if [[ ${#temp_files[@]} -ge $max_files ]]; then
                echo "WARNING: Reached max file limit ($max_files) in $dir" >&2
                break
            fi
        done < <(eval "$find_cmd" 2>/dev/null | head -"$max_files")
        
        discovered_files+=("${temp_files[@]}")
    done
    
    # Deduplicate discovered files
    if [[ ${#discovered_files[@]} -gt 0 ]]; then
        while IFS= read -r file; do
            all_files+=("$file")
        done < <(printf "%s\n" "${discovered_files[@]}" | sort -u)
    fi
    
    # Discovery phase 2: Explicit monitor files with validation
    if [[ ${#MONITOR_FILES[@]} -gt 0 ]]; then
        for file in "${MONITOR_FILES[@]}"; do
            # Skip if already added
            if [[ " ${all_files[*]} " == *" $file "* ]]; then
                continue
            fi
            
            # Validate file
            if [[ ! -f "$file" ]]; then
                echo "WARNING: Monitored file does not exist: $file" >&2
                continue
            fi
            
            if [[ ! -r "$file" ]]; then
                echo "WARNING: Monitored file not readable: $file" >&2
                continue
            fi
            
            all_files+=("$file")
        done
    fi
    
    # Output results
    if [[ ${#all_files[@]} -gt 0 ]]; then
        printf "%s\n" "${all_files[@]}" | sort -u
    else
        return 1
    fi
    
    return 0
}

# ============================================================================
# SECURITY FUNCTIONS - SIMPLIFIED VERSION
# ============================================================================

sanitize_log_line() {
    local raw_line="$1"
    local log_source="$2"
    local sanitized_line="$raw_line"
    
    # Configuration defaults
    local max_line_length="${MAX_LOG_LINE_LENGTH:-1048576}"
    local truncation_marker="...[TRUNCATED]"
    
    # Input validation
    if [[ -z "$raw_line" ]]; then
        echo ""
        return 0
    fi
    
    # Early exit for extremely long lines (performance optimization)
    local line_length=${#raw_line}
    if [[ $line_length -gt $max_line_length ]]; then
        sanitized_line="${raw_line:0:$max_line_length}${truncation_marker}"
    fi
    
    # Remove control characters
    sanitized_line=$(echo -n "$sanitized_line" | tr -d '\000-\010\013\014\016-\037\177' 2>/dev/null)
    
    # Apply pattern-based redaction
    for pattern in "${DANGEROUS_PATTERNS[@]}" "${PII_PATTERNS[@]}" "${SECRET_PATTERNS[@]}"; do
        sanitized_line=$(echo -n "$sanitized_line" | sed -E "s/$pattern/[REDACTED]/gi" 2>/dev/null)
    done
    
    echo "$sanitized_line"
    return 0
}

# ============================================================================
# GRADIENT BAR FUNCTIONS
# ============================================================================

draw_gradient_bar() {
    local value=$1
    local max=$2
    local width=$3
    local title="${4:-}"
    local bar_mode="${5:-gradient}"
    
    # Input validation
    if [[ -z "$value" ]] || [[ -z "$max" ]] || [[ "$max" -eq 0 ]]; then
        return 1
    fi
    
    # Clamp value
    ((value < 0)) && value=0
    ((value > max)) && value=$max
    
    # Calculate percentage and filled width
    local percentage_int=$((value * 100 / max))
    local filled=$((percentage_int * width / 100))
    
    # Draw the bar
    for ((i=0; i<filled; i++)); do
        if [[ $i -lt $((width/3)) ]]; then
            echo -ne "${GREEN}█"
        elif [[ $i -lt $((2*width/3)) ]]; then
            echo -ne "${YELLOW}█"
        else
            echo -ne "${RED}█"
        fi
    done
    for ((i=filled; i<width; i++)); do
        echo -ne "${DIM}░"
    done
    echo -ne "${NC}"
    
    # Add percentage
    if [[ "${SHOW_PERCENTAGE:-true}" == "true" ]]; then
        printf " ${BOLD}%3d%%${NC}" "$percentage_int"
    fi
}

# ============================================================================
# DASHBOARD RENDERING
# ============================================================================

draw_dashboard() {
    local total_errors=$(sqlite3 "$LIVE_DB" "SELECT COUNT(*) FROM metrics WHERE severity='ERROR' AND timestamp > datetime('now', '-1 minute');" 2>/dev/null || echo "0")
    local total_warnings=$(sqlite3 "$LIVE_DB" "SELECT COUNT(*) FROM metrics WHERE severity='WARNING' AND timestamp > datetime('now', '-1 minute');" 2>/dev/null || echo "0")
    local total_security=$(sqlite3 "$LIVE_DB" "SELECT COUNT(*) FROM metrics WHERE severity='SECURITY' AND timestamp > datetime('now', '-1 minute');" 2>/dev/null || echo "0")
    local active_alerts=$(sqlite3 "$LIVE_DB" "SELECT COUNT(*) FROM alerts WHERE acknowledged=0 AND timestamp > datetime('now', '-10 minutes');" 2>/dev/null || echo "0")
    
    # Move cursor to home position (top-left)
    printf "\033[H"
    
    # Header
    printf "${BOLD}${CYAN}╔═══════════════════════════════════════════════════════════════════════════════╗${NC}\n"
    printf "${BOLD}${CYAN}║                         🔍 LIVE LOG ANALYZER PRO                              ║${NC}\n"
    printf "${BOLD}${CYAN}║                    Enterprise Real-time Log Monitoring                        ║${NC}\n"
    printf "${BOLD}${CYAN}╚═══════════════════════════════════════════════════════════════════════════════╝${NC}\n"
    
    # System info line
    printf "${DIM}├─ 📍 %-15s" "$(hostname)"
    printf "├─ ⏱️  %-20s" "$(uptime -p | sed 's/up //')"
    printf "├─ 📅 %-20s" "$(date '+%H:%M:%S')"
    printf "├─ 🔄 Refresh: 1s${NC}\n"
    
    # Metrics cards
    printf "${BOLD}┌─────────────────────────────────────────────────────────────────────────────────┐${NC}\n"
    
    # Error card
    printf "${BOLD}│${NC}${RED} 🔴 ERRORS  ${NC}"
    printf "%*s" 8 ""
    printf "${BOLD}${RED}%6s${NC}" "$total_errors"
    printf "  "
    draw_gradient_bar $total_errors 100 30
    printf "  ${BOLD}│${NC}\n"
    
    # Warning card
    printf "${BOLD}│${NC}${YELLOW} 🟡 WARNINGS${NC}"
    printf "%*s" 7 ""
    printf "${BOLD}${YELLOW}%6s${NC}" "$total_warnings"
    printf "  "
    draw_gradient_bar $total_warnings 200 30
    printf "  ${BOLD}│${NC}\n"
    
    # Security card
    printf "${BOLD}│${NC}${PURPLE} ⚠️  SECURITY${NC}"
    printf "%*s" 8 ""
    printf "${BOLD}${PURPLE}%6s${NC}" "$total_security"
    printf "  "
    draw_gradient_bar $total_security 50 30
    printf "  ${BOLD}│${NC}\n"
    
    # Alert status
    printf "${BOLD}│${NC}"
    if [[ $active_alerts -gt 0 ]]; then
        printf "${RED} 🚨 ALERTS  ${NC}"
        printf "%*s" 8 ""
        printf "${BOLD}${RED}%6s${NC}" "$active_alerts"
        printf "  ${RED}${BLINK}!!! ACTIVE !!!${NC}"
    else
        printf "${GREEN} ✅ STATUS  ${NC}"
        printf "%*s" 8 ""
        printf "${BOLD}${GREEN}%6s${NC}" "OK"
        printf "  ${GREEN}System Normal${NC}"
    fi
    printf "  ${BOLD}│${NC}\n"
    printf "${BOLD}└─────────────────────────────────────────────────────────────────────────────────┘${NC}\n\n"
    
    # Threat intelligence panel
    local brute_force=$(sqlite3 "$LIVE_DB" "SELECT COUNT(*) FROM metrics WHERE message LIKE '%failed password%' AND timestamp > datetime('now', '-5 minutes');" 2>/dev/null || echo "0")
    local sql_injection=$(sqlite3 "$LIVE_DB" "SELECT COUNT(*) FROM metrics WHERE message LIKE '%SELECT%FROM%' AND timestamp > datetime('now', '-5 minutes');" 2>/dev/null || echo "0")
    local path_traversal=$(sqlite3 "$LIVE_DB" "SELECT COUNT(*) FROM metrics WHERE message LIKE '%../%' AND timestamp > datetime('now', '-5 minutes');" 2>/dev/null || echo "0")
    
    printf "${BOLD}${RED}┌─────────────────────────────────────────────────────────────────────────────────┐${NC}\n"
    printf "${BOLD}${RED}│                        🛡️  REAL-TIME THREAT INTELLIGENCE                         │${NC}\n"
    printf "${BOLD}${RED}├─────────────────────────────────────────────────────────────────────────────────┤${NC}\n"
    printf "${BOLD}${RED}│${NC}  🔐 ${RED}Brute Force:${NC} %4s" "$brute_force"
    printf "%*s" 30 ""
    printf "${BOLD}${RED}│${NC}  💉 ${RED}SQL Injection:${NC} %4s" "$sql_injection"
    printf "%*s" 28 ""
    printf "${BOLD}${RED}│${NC}  📁 ${RED}Path Traversal:${NC} %4s" "$path_traversal"
    printf "%*s" 25 ""
    printf "${BOLD}${RED}│${NC}\n"
    printf "${BOLD}${RED}└─────────────────────────────────────────────────────────────────────────────────┘${NC}\n\n"
    
    # Live log stream
    printf "${BOLD}${CYAN}┌─────────────────────────────────────────────────────────────────────────────────┐${NC}\n"
    printf "${BOLD}${CYAN}│                           📝 LIVE LOG STREAM                                    │${NC}\n"
    printf "${BOLD}${CYAN}├─────────────────────────────────────────────────────────────────────────────────┤${NC}\n"
    
    # Get recent logs
    local logs=$(sqlite3 "$LIVE_DB" "SELECT timestamp, severity, log_file, message FROM metrics ORDER BY timestamp DESC LIMIT 15;" 2>/dev/null)
    
    local line_count=0
    while IFS='|' read -r ts severity file msg; do
        if [[ -z "$ts" ]]; then continue; fi
        
        local time_only=$(echo "$ts" | cut -d' ' -f2 | cut -d'.' -f1)
        local short_file=$(basename "$file" 2>/dev/null | cut -c1-12)
        local short_msg="${msg:0:70}"
        
        case $severity in
            ERROR)
                printf "${CYAN}│${NC} ${RED}🔴${NC} ${DIM}%s${NC} " "$time_only"
                printf "${CYAN}[%-12s]${NC} " "$short_file"
                printf "${RED}%s${NC}\n" "$short_msg"
                ;;
            WARNING)
                printf "${CYAN}│${NC} ${YELLOW}🟡${NC} ${DIM}%s${NC} " "$time_only"
                printf "${CYAN}[%-12s]${NC} " "$short_file"
                printf "${YELLOW}%s${NC}\n" "$short_msg"
                ;;
            SECURITY)
                printf "${CYAN}│${NC} ${PURPLE}⚠️${NC} ${DIM}%s${NC} " "$time_only"
                printf "${CYAN}[%-12s]${NC} " "$short_file"
                printf "${PURPLE}%s${NC}\n" "$short_msg"
                ;;
            *)
                printf "${CYAN}│${NC} ${DIM}ℹ️${NC} ${DIM}%s${NC} " "$time_only"
                printf "${CYAN}[%-12s]${NC} " "$short_file"
                printf "${WHITE}%s${NC}\n" "$short_msg"
                ;;
        esac
        ((line_count++))
    done <<< "$logs"
    
    # Fill empty lines
    while [[ $line_count -lt 15 ]]; do
        printf "${CYAN}│${NC}                                                                                 ${NC}\n"
        ((line_count++))
    done
    
    printf "${BOLD}${CYAN}└─────────────────────────────────────────────────────────────────────────────────┘${NC}\n"
    
    # Hotkeys bar
    printf "\n${BOLD}${YELLOW}═══════════════════════════════════════════════════════════════════════════════${NC}\n"
    printf "${BOLD}  🎮 CONTROLS:${NC}  ${DIM}[s]${NC} Stats  ${DIM}[a]${NC} Alerts  ${DIM}[c]${NC} Clear  ${DIM}[q]${NC} Quit\n"
    printf "${BOLD}${YELLOW}═══════════════════════════════════════════════════════════════════════════════${NC}\n"
}

# ============================================================================
# ANALYSIS ENGINE
# ============================================================================

analyze_line() {
    local line="$1"
    local log_file="$2"
    local severity="INFO"
    
    line=$(sanitize_log_line "$line" "$log_file")
    
    if echo "$line" | grep -qi "error\|fail\|fatal\|panic\|critical"; then
        severity="ERROR"
        sqlite3 "$LIVE_DB" "INSERT INTO metrics (log_file, severity, message) VALUES ('$log_file', 'ERROR', '${line//\'/''}');" 2>/dev/null
        
    elif echo "$line" | grep -qi "warning\|warn"; then
        severity="WARNING"
        sqlite3 "$LIVE_DB" "INSERT INTO metrics (log_file, severity, message) VALUES ('$log_file', 'WARNING', '${line//\'/''}');" 2>/dev/null
        
    elif echo "$line" | grep -qi "attack\|brute force\|unauthorized\|authentication failure"; then
        severity="SECURITY"
        sqlite3 "$LIVE_DB" "INSERT INTO metrics (log_file, severity, message) VALUES ('$log_file', 'SECURITY', '${line//\'/''}');" 2>/dev/null
        sqlite3 "$LIVE_DB" "INSERT INTO alerts (severity, alert_type, message) VALUES ('HIGH', 'SECURITY_EVENT', 'Security event in $log_file');" 2>/dev/null
    fi
}

# ============================================================================
# STATS AND ALERTS PAGES
# ============================================================================

show_stats() {
    printf "${HIDE_CURSOR}"
    printf "\033[?1049h"
    
    clear
    echo -e "${BOLD}${CYAN}╔════════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${BOLD}${CYAN}║                    📊 ADVANCED STATISTICS                       ║${NC}"
    echo -e "${BOLD}${CYAN}╚════════════════════════════════════════════════════════════════╝${NC}\n"
    
    local total_all=$(sqlite3 "$LIVE_DB" "SELECT COUNT(*) FROM metrics;" 2>/dev/null || echo "0")
    local total_errors=$(sqlite3 "$LIVE_DB" "SELECT COUNT(*) FROM metrics WHERE severity='ERROR';" 2>/dev/null || echo "0")
    local total_warnings=$(sqlite3 "$LIVE_DB" "SELECT COUNT(*) FROM metrics WHERE severity='WARNING';" 2>/dev/null || echo "0")
    local total_security=$(sqlite3 "$LIVE_DB" "SELECT COUNT(*) FROM metrics WHERE severity='SECURITY';" 2>/dev/null || echo "0")
    local unique_files=$(sqlite3 "$LIVE_DB" "SELECT COUNT(DISTINCT log_file) FROM metrics;" 2>/dev/null || echo "0")
    
    echo -e "${BOLD}${GREEN}📈 Overall Statistics:${NC}\n"
    echo -e "  ${WHITE}📝 Total entries:${NC}     $total_all"
    echo -e "  ${RED}🔴 Errors:${NC}             $total_errors"
    echo -e "  ${YELLOW}🟡 Warnings:${NC}           $total_warnings"
    echo -e "  ${PURPLE}⚠️  Security:${NC}          $total_security"
    echo -e "  ${CYAN}📁 Log files:${NC}          $unique_files"
    
    echo -e "\n${DIM}Press any key to return...${NC}"
    read -n 1
    
    printf "\033[?1049l"
    printf "${SHOW_CURSOR}"
}

show_alerts() {
    printf "${HIDE_CURSOR}"
    printf "\033[?1049h"
    
    clear
    echo -e "${BOLD}${RED}╔════════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${BOLD}${RED}║                      🚨 ALERT MANAGEMENT                        ║${NC}"
    echo -e "${BOLD}${RED}╚════════════════════════════════════════════════════════════════╝${NC}\n"
    
    local alerts=$(sqlite3 "$LIVE_DB" "SELECT timestamp, severity, alert_type, message FROM alerts ORDER BY timestamp DESC LIMIT 20;" 2>/dev/null)
    
    if [[ -z "$alerts" ]]; then
        echo -e "${GREEN}  ✅ No active alerts! System is healthy.${NC}\n"
    else
        while IFS='|' read -r ts severity type msg; do
            echo -e "${RED}  🚨 ${BOLD}[${ts}]${NC}"
            echo -e "     ${RED}Type:${NC} $type"
            echo -e "     ${RED}Severity:${NC} $severity"
            echo -e "     ${RED}Message:${NC} ${msg:0:80}"
            echo -e "     ${DIM}────────────────────────────────────────────────────────────${NC}"
        done <<< "$alerts"
    fi
    
    echo -e "\n${DIM}Press any key to return...${NC}"
    read -n 1
    
    printf "\033[?1049l"
    printf "${SHOW_CURSOR}"
}

# ============================================================================
# MAIN MONITORING LOOP
# ============================================================================

start_monitoring() {
    local log_files=($(discover_log_files))
    local file_count=${#log_files[@]}
    
    if [[ $file_count -eq 0 ]]; then
        echo -e "${RED}No log files found! Try: sudo $0${NC}"
        exit 1
    fi
    
    # Start tail processes in background
    for log_file in "${log_files[@]}"; do
        if [[ -r "$log_file" ]]; then
            tail -n 0 -F "$log_file" 2>/dev/null | while IFS= read -r line; do
                analyze_line "$line" "$log_file"
            done &
        fi
    done
    
    # Main dashboard loop
    while true; do
        draw_dashboard
        
        # Non-blocking key read
        read -t $REFRESH_RATE -n 1 key
        if [[ $? -eq 0 ]]; then
            case $key in
                'q') 
                    exit 0
                    ;;
                's') 
                    show_stats
                    ;;
                'a') 
                    show_alerts
                    ;;
                'c') 
                    sqlite3 "$LIVE_DB" "DELETE FROM metrics WHERE timestamp < datetime('now', '-1 hour');" 2>/dev/null
                    ;;
            esac
        fi
    done
}

# ============================================================================
# MAIN
# ============================================================================

main() {
    # Parse arguments
    while [[ $# -gt 0 ]]; do
        case $1 in
            -c|--config)
                CONFIG_FILE="$2"
                shift 2
                ;;
            -t|--threshold)
                ERROR_THRESHOLD="$2"
                shift 2
                ;;
            -h|--help)
                echo "Usage: $0 [OPTIONS]"
                echo "  -c, --config FILE     Configuration file"
                echo "  -t, --threshold NUM   Error threshold per minute"
                echo "  -h, --help            Show help"
                exit 0
                ;;
            *)
                echo "Unknown option: $1"
                exit 1
                ;;
        esac
    done
    
    # Initialize
    load_config
    init_database
    init_terminal
    
    # Show startup banner briefly
    clear
    echo -e "${GREEN}${BOLD}"
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║      LIVE LOG ANALYZER PRO v${VERSION} - SMOOTH DASHBOARD         ║"
    echo "║         Like htop, but for log files!                        ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
    sleep 1
    
    # Start monitoring
    start_monitoring
}

# Run
main "$@"