#!/bin/bash

# Power Consumption Trend Analyzer v3.1
# Analyzes WittyPi power monitoring data with INA219 battery voltage tracking
# Compatible with Pi Zero 2W + 4S LiFePO4 battery
# Now includes CPU governor and core management optimization
# v3.1: Added battery health monitoring (voltage sag, cycle counting, temperature alerts)

# Configuration
DAILY_DATA_DIR="/var/log/power_daily"
DAYS_TO_ANALYZE=30
BATTERY_CYCLES_FILE="/var/log/power_daily/battery_cycles.dat"

# Battery thresholds (4S LiFePO4)
BATTERY_FULL=13.6    # Practical charging maximum (3.4V/cell)
BATTERY_GOOD=13.2    # Good charge level
BATTERY_LOW=12.4     # Low battery warning
BATTERY_CRITICAL=12.0 # Critical - recharge immediately

# Battery health thresholds
VOLTAGE_SAG_THRESHOLD=1.5      # Alert if idle-to-load voltage drop exceeds 1.5V
TEMP_CHARGING_THRESHOLD=45.0   # Alert if temperature exceeds 45°C during charge
BATTERY_RATED_CYCLES=2000      # Rated cycle life for LiFePO4
BATTERY_REPLACEMENT_PERCENT=80 # Trigger replacement alert at 80% of rated cycles

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

# Function to print section headers
print_header() {
    echo -e "\n${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${CYAN}$1${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
}

# Function to create simple ASCII bar chart
create_bar_chart() {
    local value=$1
    local max_value=$2
    local width=40
    # Reorder operations: multiply first, then divide to avoid premature truncation with scale=0
    local bar_length=$(echo "scale=0; ($value * $width) / $max_value" | bc -l 2>/dev/null || echo "0")

    printf "["
    for ((i=0; i<bar_length; i++)); do printf "█"; done
    for ((i=bar_length; i<width; i++)); do printf " "; done
    printf "]"
}

# Function to get battery status indicator
get_battery_status() {
    local voltage=$1

    if (( $(echo "$voltage >= $BATTERY_GOOD" | bc -l) )); then
        echo "${GREEN}✓ GOOD${NC}"
    elif (( $(echo "$voltage >= $BATTERY_LOW" | bc -l) )); then
        echo "${YELLOW}⚠ MODERATE${NC}"
    elif (( $(echo "$voltage >= $BATTERY_CRITICAL" | bc -l) )); then
        echo "${RED}⚠ LOW${NC}"
    else
        echo "${RED}🔴 CRITICAL${NC}"
    fi
}

# Function to get CPU status
get_cpu_status() {
    local cpu_info=()
    
    # Get governor
    local governor=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null || echo "unknown")
    
    # Get current frequency
    local freq=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq 2>/dev/null || echo "0")
    local freq_mhz=$(echo "scale=0; $freq / 1000" | bc -l 2>/dev/null || echo "0")
    
    # Count present cores (all CPU directories that exist)
    local present_cores=0
    for cpu in /sys/devices/system/cpu/cpu[0-9]*; do
        if [ -d "$cpu" ]; then
            present_cores=$((present_cores + 1))
        fi
    done
    
    # Count online cores using the kernel's online file (more reliable)
    # Format can be: "0-1" or "0,1" or "0-3" etc.
    local online_cores=0
    if [ -f /sys/devices/system/cpu/online ]; then
        local online_list=$(cat /sys/devices/system/cpu/online)
        # Parse formats like "0-1" or "0,2-3" or "0,1,2,3"
        # Simple approach: count commas and dashes to estimate
        # Better approach: expand ranges
        
        # Count CPUs by expanding the range
        for range in $(echo "$online_list" | tr ',' ' '); do
            if [[ "$range" =~ ^([0-9]+)-([0-9]+)$ ]]; then
                # Range format like "0-3"
                local start="${BASH_REMATCH[1]}"
                local end="${BASH_REMATCH[2]}"
                online_cores=$((online_cores + end - start + 1))
            else
                # Single CPU like "0"
                online_cores=$((online_cores + 1))
            fi
        done
    else
        # Fallback: assume CPU0 is online
        online_cores=1
    fi
    
    # Check if maxcpus boot parameter is limiting cores
    local maxcpus_limit="none"
    if grep -q "maxcpus=" /proc/cmdline 2>/dev/null; then
        maxcpus_limit=$(grep -o "maxcpus=[0-9]*" /proc/cmdline | cut -d'=' -f2)
    fi
    
    # Get CPU temperature
    local temp=$(cat /sys/class/thermal/thermal_zone0/temp 2>/dev/null || echo "0")
    local temp_c=$(echo "scale=1; $temp / 1000" | bc -l 2>/dev/null || echo "0")
    
    echo "${governor}|${freq_mhz}|${present_cores}|${online_cores}|${temp_c}|${maxcpus_limit}"
}

# Function to estimate CPU power consumption
estimate_cpu_power() {
    local governor=$1
    local cores=$2
    
    case "$governor" in
        "powersave")
            case "$cores" in
                "2") echo "0.3-0.4" ;;
                "4") echo "0.4-0.5" ;;
                *) echo "0.4-0.5" ;;
            esac
            ;;
        "ondemand")
            case "$cores" in
                "2") echo "0.5-0.7" ;;
                "4") echo "0.8-1.2" ;;
                *) echo "0.8-1.2" ;;
            esac
            ;;
        "performance")
            case "$cores" in
                "2") echo "0.8-1.0" ;;
                "4") echo "1.2-1.5" ;;
                *) echo "1.2-1.5" ;;
            esac
            ;;
        *)
            echo "0.4-1.2"
            ;;
    esac
}

# Function to detect CSV format (old vs new with battery data)
has_battery_data() {
    local csv_file=$1

    # Check if file has battery voltage column (column 5)
    local header=$(head -n 1 "$csv_file")
    if echo "$header" | grep -q "battery_voltage"; then
        return 0
    fi
    return 1
}

# Function to get daily statistics
get_daily_stats() {
    local date=$1
    local csv_file="$DAILY_DATA_DIR/power_${date}.csv"
    local total_file="$DAILY_DATA_DIR/total_${date}.dat"

    if [ ! -f "$csv_file" ]; then
        echo "N/A|N/A|N/A|N/A|N/A|N/A|N/A"
        return 1
    fi

    local total_wh=$(cat "$total_file" 2>/dev/null || echo "0")

    # Check if this CSV has battery data
    if has_battery_data "$csv_file"; then
        # New format with battery voltage (column 5) and battery percent (column 6)
        local stats=$(awk -F',' 'NR>1 {
            sum+=$2;
            count++;
            if($2>max_power || max_power=="") max_power=$2;
            if($2<min_power || min_power=="" || min_power==0) min_power=$2;
            if($5>0) {
                if($5<min_batt || min_batt=="" || min_batt==0) min_batt=$5;
                if($5>max_batt || max_batt=="") max_batt=$5;
            }
        } END {
            avg=(count>0) ? sum/count : 0;
            printf "%.3f|%.3f|%.3f|%d|%.2f|%.2f", avg, max_power, min_power, count, min_batt, max_batt
        }' "$csv_file")
    else
        # Old format without battery data
        local stats=$(awk -F',' 'NR>1 {
            sum+=$2;
            count++;
            if($2>max || max=="") max=$2;
            if($2<min || min=="" || min==0) min=$2
        } END {
            avg=(count>0) ? sum/count : 0;
            printf "%.3f|%.3f|%.3f|%d|0|0", avg, max, min, count
        }' "$csv_file")
    fi

    echo "${total_wh}|${stats}"
}

# Function to analyze battery voltage trends
analyze_battery_trends() {
    print_header "🔋 BATTERY VOLTAGE TREND ANALYSIS"

    echo -e "${YELLOW}Analyzing battery voltage trends...${NC}\n"

    # Collect battery data for available days
    local dates=()
    local min_voltages=()
    local max_voltages=()

    for i in $(seq 7 -1 0); do
        local date=$(date -d "$i days ago" '+%Y-%m-%d')
        local csv_file="$DAILY_DATA_DIR/power_${date}.csv"

        if [ -f "$csv_file" ] && has_battery_data "$csv_file"; then
            local stats=$(get_daily_stats "$date")
            local min_v=$(echo "$stats" | cut -d'|' -f6)
            local max_v=$(echo "$stats" | cut -d'|' -f7)

            if [ "$min_v" != "0" ] && [ "$max_v" != "0" ]; then
                dates+=("$date")
                min_voltages+=("$min_v")
                max_voltages+=("$max_v")
            fi
        fi
    done

    if [ ${#dates[@]} -eq 0 ]; then
        echo -e "${RED}No battery voltage data available.${NC}"
        echo -e "${YELLOW}Note: Battery monitoring may not be active yet.${NC}"
        return 1
    fi

    # Display battery voltage chart
    echo -e "${GREEN}Daily Battery Voltage Range (12V battery):${NC}\n"
    echo "Date       Min Voltage  Max Voltage  Status"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

    for i in "${!dates[@]}"; do
        local date="${dates[$i]}"
        local min_v="${min_voltages[$i]}"
        local max_v="${max_voltages[$i]}"
        local day_name=$(date -d "$date" '+%a')
        local status=$(get_battery_status "$min_v")

        printf "%-10s %6.2fV      %6.2fV      " "$date" "$min_v" "$max_v"
        echo -e "$status"
    done

    # Calculate battery health indicators
    echo ""
    echo -e "${BLUE}Battery Health Analysis:${NC}"

    local latest_min="${min_voltages[-1]}"
    local earliest_min="${min_voltages[0]}"
    local voltage_drop=$(echo "scale=3; $earliest_min - $latest_min" | bc -l)

    echo -e "  Current minimum voltage: ${CYAN}${latest_min}V${NC}"

    if (( $(echo "$latest_min >= $BATTERY_FULL" | bc -l) )); then
        echo -e "  Battery status: ${GREEN}✓ FULLY CHARGED (≥13.6V)${NC}"
    elif (( $(echo "$latest_min >= $BATTERY_GOOD" | bc -l) )); then
        echo -e "  Battery status: ${GREEN}✓ GOOD (13.2-13.6V)${NC}"
    elif (( $(echo "$latest_min >= $BATTERY_LOW" | bc -l) )); then
        echo -e "  Battery status: ${YELLOW}⚠ MODERATE (12.4-13.2V)${NC}"
    elif (( $(echo "$latest_min >= $BATTERY_CRITICAL" | bc -l) )); then
        echo -e "  Battery status: ${RED}⚠ LOW (12.0-12.4V) - Recharge recommended${NC}"
    else
        echo -e "  Battery status: ${RED}🔴 CRITICAL (<12.0V) - Recharge immediately!${NC}"
    fi

    # Trend analysis
    echo ""
    if (( $(echo "$voltage_drop > 0.5" | bc -l) )); then
        echo -e "  ${RED}⚠ WARNING: Battery voltage dropped ${voltage_drop}V over ${#dates[@]} days${NC}"
        echo -e "     Solar charging may not be keeping up with consumption"
    elif (( $(echo "$voltage_drop > 0.2" | bc -l) )); then
        echo -e "  ${YELLOW}⚠ NOTICE: Battery voltage dropped ${voltage_drop}V over ${#dates[@]} days${NC}"
        echo -e "     Monitor solar charging performance"
    elif (( $(echo "$voltage_drop < -0.1" | bc -l) )); then
        local voltage_gain=$(echo "scale=3; $voltage_drop * -1" | bc -l)
        echo -e "  ${GREEN}✓ Battery voltage increased ${voltage_gain}V over ${#dates[@]} days${NC}"
        echo -e "     Solar charging is working well"
    else
        echo -e "  ${GREEN}✓ Battery voltage is stable (${voltage_drop}V change)${NC}"
        echo -e "     Solar charging is balanced with consumption"
    fi

    # Solar sufficiency check
    echo ""
    echo -e "${BLUE}Solar Charging Assessment:${NC}"

    local stable_days=0
    for i in "${!min_voltages[@]}"; do
        if (( $(echo "${min_voltages[$i]} >= 12.8" | bc -l) )); then
            stable_days=$((stable_days + 1))
        fi
    done

    local stability_percent=$(echo "scale=0; ($stable_days * 100) / ${#dates[@]}" | bc -l)

    if [ $stability_percent -ge 80 ]; then
        echo -e "  ${GREEN}✓ Solar panels are adequate (${stability_percent}% days above 12.8V)${NC}"
    elif [ $stability_percent -ge 50 ]; then
        echo -e "  ${YELLOW}⚠ Solar may be marginal (${stability_percent}% days above 12.8V)${NC}"
    else
        echo -e "  ${RED}⚠ Solar insufficient (${stability_percent}% days above 12.8V)${NC}"
    fi
}

# Function to analyze trends
analyze_trends() {
    print_header "📊 POWER CONSUMPTION TREND ANALYSIS"

    echo -e "${YELLOW}Analyzing last ${DAYS_TO_ANALYZE} days of power consumption...${NC}\n"

    # Build arrays for analysis
    local dates=()
    local daily_wh=()
    local avg_power=()
    local max_power_vals=()

    for i in $(seq $DAYS_TO_ANALYZE -1 0); do
        local date=$(date -d "$i days ago" '+%Y-%m-%d')
        local stats=$(get_daily_stats "$date")

        if [ "$stats" != "N/A|N/A|N/A|N/A|N/A|N/A|N/A" ]; then
            dates+=("$date")
            daily_wh+=($(echo "$stats" | cut -d'|' -f1))
            avg_power+=($(echo "$stats" | cut -d'|' -f2))
            max_power_vals+=($(echo "$stats" | cut -d'|' -f3))
        fi
    done

    if [ ${#dates[@]} -eq 0 ]; then
        echo -e "${RED}No data available for analysis.${NC}"
        return 1
    fi

    # Display summary table
    echo -e "${GREEN}Last 7 days summary:${NC}\n"
    echo "Date       Day   Daily Wh   Avg Power   Max Power"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

    local display_limit=$((${#dates[@]} < 7 ? ${#dates[@]} : 7))
    for i in $(seq $((${#dates[@]} - 1)) -1 $((${#dates[@]} - display_limit))); do
        local date="${dates[$i]}"
        local day_name=$(date -d "$date" '+%a')
        local wh="${daily_wh[$i]}"
        local avg="${avg_power[$i]}"
        local max="${max_power_vals[$i]}"

        printf "%-10s %-5s %7.1f    %6.3f W     %5.3f W\n" "$date" "$day_name" "$wh" "$avg" "$max"
    done

    # Calculate statistics
    local sum=0
    local count=0
    for wh in "${daily_wh[@]}"; do
        sum=$(echo "$sum + $wh" | bc -l)
        count=$((count + 1))
    done

    local avg_daily=$(echo "scale=2; $sum / $count" | bc -l)

    echo ""
    echo -e "${BLUE}Consumption Statistics:${NC}"
    echo -e "  Average daily:  ${CYAN}${avg_daily} Wh${NC}"
    echo -e "  Days analyzed:  ${count}"

    # Calculate trend
    if [ ${#daily_wh[@]} -ge 3 ]; then
        local recent_avg=$(echo "scale=2; (${daily_wh[-1]} + ${daily_wh[-2]} + ${daily_wh[-3]}) / 3" | bc -l)
        local older_avg=$(echo "scale=2; (${daily_wh[0]} + ${daily_wh[1]} + ${daily_wh[2]}) / 3" | bc -l)
        local trend=$(echo "scale=2; $recent_avg - $older_avg" | bc -l)

        echo ""
        if (( $(echo "$trend > 5" | bc -l) )); then
            echo -e "  ${YELLOW}↗ Consumption increasing (+${trend} Wh/day trend)${NC}"
        elif (( $(echo "$trend < -5" | bc -l) )); then
            local abs_trend=$(echo "scale=2; $trend * -1" | bc -l)
            echo -e "  ${GREEN}↘ Consumption decreasing (-${abs_trend} Wh/day trend)${NC}"
        else
            echo -e "  ${GREEN}→ Consumption stable (${trend} Wh/day change)${NC}"
        fi
    fi
}

# Function to analyze hourly patterns
analyze_hourly_patterns() {
    print_header "🕐 HOURLY POWER CONSUMPTION PATTERNS"

    local today=$(date '+%Y-%m-%d')
    local csv_file="$DAILY_DATA_DIR/power_${today}.csv"

    if [ ! -f "$csv_file" ]; then
        echo -e "${RED}No data available for today.${NC}"
        return 1
    fi

    echo -e "${YELLOW}Analyzing today's hourly patterns...${NC}\n"

    # Create hourly buckets
    declare -A hourly_sum
    declare -A hourly_count

    while IFS=',' read -r timestamp power rest; do
        if [[ "$timestamp" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2} ]]; then
            local hour=$(echo "$timestamp" | cut -d' ' -f2 | cut -d':' -f1)
            hourly_sum[$hour]=$(echo "${hourly_sum[$hour]:-0} + $power" | bc -l)
            hourly_count[$hour]=$((${hourly_count[$hour]:-0} + 1))
        fi
    done < <(tail -n +2 "$csv_file")

    # Display hourly averages
    echo -e "${GREEN}Average power consumption by hour:${NC}\n"
    echo "Hour    Avg Power   Activity"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

    for hour in $(seq -w 0 23); do
        if [ -n "${hourly_sum[$hour]}" ]; then
            local avg=$(echo "scale=3; ${hourly_sum[$hour]} / ${hourly_count[$hour]}" | bc -l)
            printf "%s:00   %6.3f W   " "$hour" "$avg"

            # Show activity bar
            create_bar_chart "$avg" "5.0"
            echo ""
        fi
    done
}

# Function to estimate battery runtime
estimate_battery_runtime() {
    print_header "⏱️  BATTERY RUNTIME ESTIMATION"

    echo -e "${YELLOW}Calculating battery runtime based on current usage...${NC}\n"

    # Get recent average consumption
    local dates=()
    local daily_wh=()

    for i in $(seq 7 -1 0); do
        local date=$(date -d "$i days ago" '+%Y-%m-%d')
        local stats=$(get_daily_stats "$date")

        if [ "$stats" != "N/A|N/A|N/A|N/A|N/A|N/A|N/A" ]; then
            dates+=("$date")
            daily_wh+=($(echo "$stats" | cut -d'|' -f1))
        fi
    done

    if [ ${#daily_wh[@]} -eq 0 ]; then
        echo -e "${RED}No data available for estimation.${NC}"
        return 1
    fi

    # Calculate average daily consumption
    local sum=0
    for wh in "${daily_wh[@]}"; do
        sum=$(echo "$sum + $wh" | bc -l)
    done
    local daily_consumption=$(echo "scale=2; $sum / ${#daily_wh[@]}" | bc -l)
    local hourly_consumption=$(echo "scale=3; $daily_consumption / 24" | bc -l)

    echo -e "${BLUE}Current Consumption:${NC}"
    echo -e "  Daily average:  ${CYAN}${daily_consumption} Wh${NC}"
    echo -e "  Hourly average: ${CYAN}${hourly_consumption} Wh${NC}"
    echo ""

    # Battery capacity estimation (100Ah at 12.8V nominal)
    local battery_capacity_wh=1280  # 100Ah × 12.8V
    local usable_capacity_wh=1024   # 80% DoD (depth of discharge)

    echo -e "${BLUE}Battery Capacity (100Ah LiFePO4):${NC}"
    echo -e "  Total capacity:  ${GREEN}${battery_capacity_wh} Wh${NC}"
    echo -e "  Usable (80% DoD): ${GREEN}${usable_capacity_wh} Wh${NC}"
    echo ""

    # Calculate runtime from different charge levels
    local runtime_from_full=$(echo "scale=1; $usable_capacity_wh / $hourly_consumption" | bc -l)
    local runtime_from_80=$(echo "scale=1; ($usable_capacity_wh * 0.8) / $hourly_consumption" | bc -l)
    local runtime_from_50=$(echo "scale=1; ($usable_capacity_wh * 0.5) / $hourly_consumption" | bc -l)

    echo -e "${BLUE}Estimated Runtime (without solar):${NC}"
    echo -e "  From 100% charge: ${CYAN}${runtime_from_full} hours${NC} (~$(echo "scale=1; $runtime_from_full / 24" | bc -l) days)"
    echo -e "  From 80% charge:  ${CYAN}${runtime_from_80} hours${NC} (~$(echo "scale=1; $runtime_from_80 / 24" | bc -l) days)"
    echo -e "  From 50% charge:  ${CYAN}${runtime_from_50} hours${NC} (~$(echo "scale=1; $runtime_from_50 / 24" | bc -l) days)"
    echo ""

    echo -e "${BLUE}Solar Charging (2x 30W panels):${NC}"
    echo -e "  Peak generation: ${GREEN}60W${NC}"
    echo -e "  Daily (4-5h sun): ${GREEN}168-210 Wh${NC} (estimated)"
    echo -e "  Your daily use:   ${CYAN}${daily_consumption} Wh${NC}"
    echo ""

    local solar_surplus=$(echo "scale=1; 180 - $daily_consumption" | bc -l)
    if (( $(echo "$solar_surplus > 50" | bc -l) )); then
        echo -e "  ${GREEN}✓ Solar provides ~${solar_surplus}Wh surplus - excellent margin${NC}"
    elif (( $(echo "$solar_surplus > 0" | bc -l) )); then
        echo -e "  ${GREEN}✓ Solar provides ~${solar_surplus}Wh surplus - adequate${NC}"
    else
        local deficit=$(echo "scale=1; $solar_surplus * -1" | bc -l)
        echo -e "  ${RED}⚠ Solar deficit of ~${deficit}Wh - may not sustain${NC}"
    fi
}

# Function to show CPU power optimization status
cpu_power_optimization() {
    print_header "🔧 CPU POWER OPTIMIZATION STATUS"

    echo -e "${YELLOW}Analyzing CPU configuration and power savings...${NC}\n"

    # Get CPU status
    local cpu_status=$(get_cpu_status)
    local governor=$(echo "$cpu_status" | cut -d'|' -f1)
    local freq_mhz=$(echo "$cpu_status" | cut -d'|' -f2)
    local present_cores=$(echo "$cpu_status" | cut -d'|' -f3)
    local online_cores=$(echo "$cpu_status" | cut -d'|' -f4)
    local temp_c=$(echo "$cpu_status" | cut -d'|' -f5)
    local maxcpus_limit=$(echo "$cpu_status" | cut -d'|' -f6)

    # Display current configuration
    echo -e "${BLUE}Current CPU Configuration:${NC}"
    echo -e "  Governor:      ${CYAN}${governor}${NC}"
    echo -e "  Frequency:     ${CYAN}${freq_mhz} MHz${NC}"
    
    if [ "$online_cores" -ne "$present_cores" ]; then
        if [ "$maxcpus_limit" != "none" ]; then
            echo -e "  Active cores:  ${CYAN}${online_cores} / ${present_cores}${NC} ${GREEN}(maxcpus=$maxcpus_limit in cmdline.txt)${NC}"
        else
            echo -e "  Active cores:  ${CYAN}${online_cores} / ${present_cores}${NC} ${GREEN}(runtime disabled)${NC}"
        fi
    else
        echo -e "  Active cores:  ${CYAN}${online_cores} / ${present_cores}${NC}"
    fi
    
    echo -e "  Temperature:   ${CYAN}${temp_c}°C${NC}"
    echo ""

    # Estimate current CPU power
    local current_power=$(estimate_cpu_power "$governor" "$online_cores")
    echo -e "${BLUE}Estimated CPU Power Draw:${NC}"
    echo -e "  Current config: ${CYAN}${current_power} W${NC}"
    echo ""

    # Show power savings opportunities
    echo -e "${GREEN}Power Optimization Status:${NC}\n"

    local optimizations_needed=0

    # Check governor
    if [ "$governor" != "powersave" ]; then
        optimizations_needed=1
        local powersave_power=$(estimate_cpu_power "powersave" "$online_cores")
        echo -e "${YELLOW}⚡ CPU Governor Optimization Available:${NC}"
        echo -e "   Current ($governor):  ${current_power} W"
        echo -e "   With powersave:       ${powersave_power} W"
        echo -e "   ${GREEN}Potential savings: ~0.3-0.4 W (~7-10 Wh/day)${NC}"
        echo ""
        echo -e "   ${CYAN}To enable powersave mode:${NC}"
        echo -e "   1. Install cpufrequtils:"
        echo -e "      sudo apt install cpufrequtils"
        echo ""
        echo -e "   2. Create systemd service:"
        echo -e "      sudo nano /etc/systemd/system/cpufreq-powersave.service"
        echo ""
        echo -e "   3. Add the following:"
        echo -e "      [Unit]"
        echo -e "      Description=Set CPU governor to powersave"
        echo -e "      After=multi-user.target"
        echo ""
        echo -e "      [Service]"
        echo -e "      Type=oneshot"
        echo -e "      ExecStart=/usr/bin/cpufreq-set -g powersave -r"
        echo -e "      RemainAfterExit=yes"
        echo ""
        echo -e "      [Install]"
        echo -e "      WantedBy=multi-user.target"
        echo ""
        echo -e "   4. Enable and start:"
        echo -e "      sudo systemctl daemon-reload"
        echo -e "      sudo systemctl enable cpufreq-powersave.service"
        echo -e "      sudo systemctl start cpufreq-powersave.service"
        echo ""
    else
        echo -e "${GREEN}✓ CPU governor set to powersave${NC}"
        echo ""
    fi

    # Check core count
    if [ "$online_cores" -gt 2 ]; then
        optimizations_needed=1
        local two_core_power=$(estimate_cpu_power "$governor" "2")
        echo -e "${YELLOW}⚡ CPU Core Reduction Available:${NC}"
        echo -e "   Current ($online_cores cores):  ${current_power} W"
        echo -e "   With 2 cores:          ${two_core_power} W"
        echo -e "   ${GREEN}Potential savings: ~0.1-0.2 W (~2-5 Wh/day)${NC}"
        echo ""
        echo -e "   ${CYAN}To limit to 2 cores at boot (recommended):${NC}"
        echo -e "   1. Edit boot config:"
        echo -e "      sudo nano /boot/firmware/cmdline.txt"
        echo ""
        echo -e "   2. Add to the end of the single line:"
        echo -e "      maxcpus=2"
        echo ""
        echo -e "   3. Reboot:"
        echo -e "      sudo reboot"
        echo ""
        echo -e "   ${MAGENTA}Note: Your OpenCurb workload (camera, BLE, modem) is I/O-bound,"
        echo -e "   so 2 cores are sufficient for all operations.${NC}"
        echo ""
    elif [ "$online_cores" -le 2 ]; then
        if [ "$maxcpus_limit" == "2" ]; then
            echo -e "${GREEN}✓ CPU cores limited to 2 via maxcpus boot parameter${NC}"
        else
            echo -e "${GREEN}✓ CPU cores limited to 2 (runtime disabled)${NC}"
        fi
        echo ""
    fi

    # Calculate combined savings if optimizations needed
    if [ $optimizations_needed -eq 1 ]; then
        local optimized_power=$(estimate_cpu_power "powersave" "2")
        echo -e "${GREEN}Combined Optimization Potential:${NC}"
        echo -e "  Current total:    ${current_power} W"
        echo -e "  Fully optimized:  ${optimized_power} W"
        echo -e "  ${GREEN}Total savings: ~0.4-0.6 W (~10-15 Wh/day)${NC}"
        echo ""
        echo -e "  ${BLUE}Impact on battery runtime:${NC}"
        echo -e "  With 100Ah battery, this extends runtime by ~10-20 hours"
        echo -e "  or reduces solar panel requirements proportionally"
    else
        echo -e "${GREEN}✓ CPU fully optimized for power savings!${NC}"
        echo ""
        echo -e "  ${BLUE}Current optimization saves approximately:${NC}"
        local unoptimized_power=$(estimate_cpu_power "ondemand" "4")
        echo -e "  Baseline (4 cores, ondemand):  ${unoptimized_power} W"
        echo -e "  Your config:                   ${current_power} W"
        echo -e "  ${GREEN}Total savings: ~0.4-0.6 W (~10-15 Wh/day)${NC}"
    fi
}

# Function to check battery health (voltage sag, cycles, temperature)
battery_health_check() {
    print_header "🔋 BATTERY HEALTH CHECK"

    echo -e "${YELLOW}Analyzing battery health indicators...${NC}\n"

    local health_issues=0

    # === VOLTAGE SAG DETECTION ===
    echo -e "${BLUE}1. Voltage Sag Analysis (Internal Resistance Test):${NC}\n"

    # Analyze last 7 days for voltage sag patterns
    local sag_days=0
    local max_sag=0
    local sag_date=""

    for i in $(seq 6 -1 0); do
        local date=$(date -d "$i days ago" '+%Y-%m-%d')
        local csv_file="$DAILY_DATA_DIR/power_${date}.csv"

        if [ -f "$csv_file" ] && has_battery_data "$csv_file"; then
            # Calculate voltage differential (max - min) for the day
            local stats=$(get_daily_stats "$date")
            local min_v=$(echo "$stats" | cut -d'|' -f6)
            local max_v=$(echo "$stats" | cut -d'|' -f7)

            if [ "$min_v" != "0" ] && [ "$max_v" != "0" ]; then
                local voltage_diff=$(echo "scale=2; $max_v - $min_v" | bc -l)

                # Check if sag exceeds threshold
                if (( $(echo "$voltage_diff > $VOLTAGE_SAG_THRESHOLD" | bc -l) )); then
                    sag_days=$((sag_days + 1))

                    # Track maximum sag
                    if (( $(echo "$voltage_diff > $max_sag" | bc -l) )); then
                        max_sag=$voltage_diff
                        sag_date=$date
                    fi
                fi
            fi
        fi
    done

    if [ $sag_days -gt 0 ]; then
        health_issues=$((health_issues + 1))
        echo -e "  ${RED}⚠ VOLTAGE SAG DETECTED${NC}"
        echo -e "  Days with >1.5V sag: ${RED}${sag_days}/7 days${NC}"
        echo -e "  Maximum sag: ${RED}${max_sag}V${NC} on $sag_date"
        echo ""
        echo -e "  ${YELLOW}Analysis:${NC}"
        echo -e "    Voltage sag >1.5V indicates high internal resistance."
        echo -e "    Battery cells are degraded and cannot deliver peak current."
        echo -e "    This can cause boot loops and system instability."
        echo ""
        echo -e "  ${MAGENTA}Recommendation: REPLACE BATTERY IMMEDIATELY${NC}"
        echo ""
    else
        echo -e "  ${GREEN}✓ No voltage sag detected (healthy internal resistance)${NC}"
        echo -e "  All days show <1.5V differential between idle and loaded voltage"
        echo ""
    fi

    # === CHARGE/DISCHARGE CYCLE COUNTING ===
    echo -e "${BLUE}2. Battery Cycle Count:${NC}\n"

    # Initialize or read cycle counter
    local cycle_count=0
    if [ -f "$BATTERY_CYCLES_FILE" ]; then
        cycle_count=$(cat "$BATTERY_CYCLES_FILE" 2>/dev/null || echo "0")
    else
        # Create file with initial count (estimate based on deployment date if known)
        echo "0" > "$BATTERY_CYCLES_FILE"
        echo -e "  ${YELLOW}Cycle counter initialized at 0${NC}"
        echo -e "  ${YELLOW}Note: Update manually if battery has existing cycles${NC}"
        echo ""
    fi

    # Count charge cycles from recent data (look for voltage transitions from low to high)
    # A cycle is defined as: voltage dropping below 12.4V then charging back above 13.2V
    local new_cycles=0
    local last_was_low=false

    for i in $(seq 29 -1 0); do
        local date=$(date -d "$i days ago" '+%Y-%m-%d')
        local csv_file="$DAILY_DATA_DIR/power_${date}.csv"

        if [ -f "$csv_file" ] && has_battery_data "$csv_file"; then
            local stats=$(get_daily_stats "$date")
            local min_v=$(echo "$stats" | cut -d'|' -f6)
            local max_v=$(echo "$stats" | cut -d'|' -f7)

            # Check for discharge/charge cycle
            if [ "$min_v" != "0" ] && [ "$max_v" != "0" ]; then
                if (( $(echo "$min_v < 12.4" | bc -l) )); then
                    last_was_low=true
                fi

                if [ "$last_was_low" = true ] && (( $(echo "$max_v > 13.2" | bc -l) )); then
                    new_cycles=$((new_cycles + 1))
                    last_was_low=false
                fi
            fi
        fi
    done

    # Update cycle count if new cycles detected
    if [ $new_cycles -gt 0 ]; then
        cycle_count=$((cycle_count + new_cycles))
        echo "$cycle_count" > "$BATTERY_CYCLES_FILE"
        echo -e "  ${CYAN}Detected $new_cycles new charge cycle(s) in last 30 days${NC}"
    fi

    local cycle_percent=$(echo "scale=1; ($cycle_count * 100) / $BATTERY_RATED_CYCLES" | bc -l)
    local replacement_threshold=$(echo "scale=0; $BATTERY_RATED_CYCLES * $BATTERY_REPLACEMENT_PERCENT / 100" | bc -l)

    echo -e "  Current cycle count: ${CYAN}${cycle_count}${NC}"
    echo -e "  Rated cycle life: ${CYAN}${BATTERY_RATED_CYCLES}${NC} cycles"
    echo -e "  Battery usage: ${CYAN}${cycle_percent}%${NC}"
    echo ""

    if [ $cycle_count -ge $replacement_threshold ]; then
        health_issues=$((health_issues + 1))
        echo -e "  ${RED}⚠ REPLACEMENT THRESHOLD REACHED${NC}"
        echo -e "  Battery has exceeded ${BATTERY_REPLACEMENT_PERCENT}% of rated cycle life"
        echo -e "  ${MAGENTA}Recommendation: Schedule battery replacement${NC}"
        echo ""
    elif (( $(echo "$cycle_percent > 60" | bc -l) )); then
        echo -e "  ${YELLOW}⚠ Battery aging (>60% of cycle life used)${NC}"
        echo -e "  Monitor voltage sag and capacity degradation closely"
        echo ""
    else
        echo -e "  ${GREEN}✓ Battery within acceptable cycle life (<60% used)${NC}"
        echo ""
    fi

    # === TEMPERATURE MONITORING ===
    echo -e "${BLUE}3. Battery Temperature Analysis:${NC}\n"

    local temp_alerts=0
    local max_temp=0
    local max_temp_date=""

    # Check last 7 days for high temperature events
    for i in $(seq 6 -1 0); do
        local date=$(date -d "$i days ago" '+%Y-%m-%d')
        local csv_file="$DAILY_DATA_DIR/power_${date}.csv"

        if [ -f "$csv_file" ] && has_battery_data "$csv_file"; then
            # Find maximum temperature for the day when battery is charging (voltage increasing)
            local day_max_temp=$(awk -F',' -v charging_threshold="$BATTERY_GOOD" '
                NR>1 && $5 > charging_threshold && $7 > 0 {
                    if ($7 > max_temp) max_temp = $7
                }
                END { print (max_temp > 0) ? max_temp : 0 }
            ' "$csv_file")

            if (( $(echo "$day_max_temp > $TEMP_CHARGING_THRESHOLD" | bc -l) )); then
                temp_alerts=$((temp_alerts + 1))

                if (( $(echo "$day_max_temp > $max_temp" | bc -l) )); then
                    max_temp=$day_max_temp
                    max_temp_date=$date
                fi
            fi
        fi
    done

    if [ $temp_alerts -gt 0 ]; then
        health_issues=$((health_issues + 1))
        echo -e "  ${RED}⚠ HIGH TEMPERATURE DETECTED${NC}"
        echo -e "  Days with temp >45°C: ${RED}${temp_alerts}/7 days${NC}"
        echo -e "  Maximum temperature: ${RED}${max_temp}°C${NC} on $max_temp_date"
        echo ""
        echo -e "  ${YELLOW}Analysis:${NC}"
        echo -e "    High temperature during charging indicates increased internal"
        echo -e "    resistance causing I²R heating (power loss as heat)."
        echo -e "    This accelerates battery degradation and reduces lifespan."
        echo ""
        echo -e "  ${MAGENTA}Recommendation: Check battery health, consider replacement${NC}"
        echo ""
    else
        echo -e "  ${GREEN}✓ Temperature within safe limits (<45°C during charge)${NC}"
        echo ""
    fi

    # === OVERALL HEALTH SUMMARY ===
    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
    echo -e "${BLUE}Overall Battery Health Summary:${NC}\n"

    if [ $health_issues -eq 0 ]; then
        echo -e "  ${GREEN}✓✓✓ BATTERY HEALTHY ✓✓✓${NC}"
        echo ""
        echo -e "  All health indicators are within normal ranges:"
        echo -e "    • No voltage sag detected (internal resistance good)"
        echo -e "    • Cycle count within acceptable range"
        echo -e "    • Temperature within safe limits"
        echo ""
        echo -e "  ${CYAN}Recommended Action: Continue normal monitoring${NC}"
    elif [ $health_issues -eq 1 ]; then
        echo -e "  ${YELLOW}⚠ BATTERY DEGRADATION DETECTED ⚠${NC}"
        echo ""
        echo -e "  One health indicator shows degradation."
        echo -e "  ${CYAN}Recommended Action: Increase monitoring frequency${NC}"
        echo -e "  ${CYAN}Consider replacement within 3-6 months${NC}"
    else
        echo -e "  ${RED}🔴🔴🔴 BATTERY FAILURE IMMINENT 🔴🔴🔴${NC}"
        echo ""
        echo -e "  Multiple health indicators show battery degradation:"
        echo -e "    $health_issues out of 3 health checks failed"
        echo ""
        echo -e "  ${MAGENTA}CRITICAL: Replace battery immediately to prevent:${NC}"
        echo -e "    • Boot loops and system instability"
        echo -e "    • Unexpected shutdowns"
        echo -e "    • Data loss"
        echo -e "    • Complete system failure"
        echo ""
        echo -e "  ${RED}DO NOT DEPLOY THIS UNIT TO THE FIELD${NC}"
    fi

    echo -e "${BLUE}═══════════════════════════════════════════════════════════${NC}"
}

# Function to show component power breakdown
component_breakdown() {
    print_header "⚡ COMPONENT POWER ANALYSIS"

    echo -e "${YELLOW}Typical power consumption by component:${NC}\n"

    # Get current CPU config for accurate estimates
    local cpu_status=$(get_cpu_status)
    local governor=$(echo "$cpu_status" | cut -d'|' -f1)
    local present_cores=$(echo "$cpu_status" | cut -d'|' -f3)
    local online_cores=$(echo "$cpu_status" | cut -d'|' -f4)
    local cpu_power=$(estimate_cpu_power "$governor" "$online_cores")

    echo -e "${GREEN}CPU Configuration (Pi Zero 2W):${NC}"
    echo "  Governor: $governor | Cores: $online_cores/$present_cores online"
    echo "  Current power:         $cpu_power W"
    echo ""
    echo -e "${GREEN}Other Fixed Components:${NC}"
    echo "  WittyPi HAT:           0.01 - 0.02 W"
    echo ""
    echo -e "${GREEN}Variable Components:${NC}"
    echo "  USB Camera (idle):     0.1 - 0.2 W"
    echo "  USB Camera (active):   0.5 - 1.5 W"
    echo "  LTE Modem (idle):      0.1 - 0.3 W"
    echo "  LTE Modem (active):    1.0 - 3.0 W"
    echo "  LTE Modem (transmit):  2.0 - 4.0 W (peaks)"
    echo "  BLE Scanner:           0.05 - 0.15 W"
    echo "  Ultrasonic Sensor:     0.01 - 0.05 W"
    echo "  USB Hub:               0.05 - 0.1 W"
    echo ""

    # Analyze power spikes
    local today=$(date '+%Y-%m-%d')
    local csv_file="$DAILY_DATA_DIR/power_${today}.csv"

    if [ -f "$csv_file" ]; then
        local peaks=$(awk -F',' 'NR>1 && $2>3.5 {count++} END {print count+0}' "$csv_file")
        local total_samples=$(awk -F',' 'NR>1 {count++} END {print count}' "$csv_file")

        if [ $total_samples -gt 0 ]; then
            local spike_percent=$(echo "scale=1; ($peaks / $total_samples) * 100" | bc -l)

            echo -e "${BLUE}Today's Activity Analysis:${NC}"
            echo -e "  Power spikes >3.5W:  ${peaks}/${total_samples} samples (${spike_percent}%)"

            if (( $(echo "$spike_percent > 10" | bc -l) )); then
                echo -e "  ${YELLOW}↗ High modem/camera activity detected${NC}"
            else
                echo -e "  ${GREEN}→ Normal activity levels${NC}"
            fi
        fi
    fi
}

# Function to show current status
current_status() {
    print_header "📡 CURRENT SYSTEM STATUS"

    local today=$(date '+%Y-%m-%d')
    local csv_file="$DAILY_DATA_DIR/power_${today}.csv"

    if [ ! -f "$csv_file" ]; then
        echo -e "${RED}No data available for today.${NC}"
        return 1
    fi

    # Get latest reading
    local latest=$(tail -n 1 "$csv_file")
    local timestamp=$(echo "$latest" | cut -d',' -f1)
    local power=$(echo "$latest" | cut -d',' -f2)
    local supply_voltage=$(echo "$latest" | cut -d',' -f3)
    local current=$(echo "$latest" | cut -d',' -f4)

    echo -e "${GREEN}Latest Reading:${NC} $timestamp"
    echo ""
    echo -e "  Power:          ${CYAN}${power} W${NC}"
    echo -e "  Supply Voltage: ${CYAN}${supply_voltage} V${NC} (5V rail)"
    echo -e "  Current:        ${CYAN}${current} A${NC}"

    # Check if we have battery data
    if has_battery_data "$csv_file"; then
        local battery_voltage=$(echo "$latest" | cut -d',' -f5)
        local battery_percent=$(echo "$latest" | cut -d',' -f6)
        local temp=$(echo "$latest" | cut -d',' -f7)
        local cumulative=$(echo "$latest" | cut -d',' -f9)

        echo -e "  Battery Voltage: ${MAGENTA}${battery_voltage} V${NC} (12V battery)"
        echo -e "  Battery Level:   ${MAGENTA}${battery_percent}%${NC}"
        echo -e "  Temperature:     ${CYAN}${temp} °C${NC}"
    else
        local temp=$(echo "$latest" | cut -d',' -f5)
        local cumulative=$(echo "$latest" | cut -d',' -f7)
        echo -e "  Temperature:     ${CYAN}${temp} °C${NC}"
    fi

    echo ""
    echo -e "  Today's total: ${GREEN}${cumulative} Wh${NC}"

    # Get CPU status
    local cpu_status=$(get_cpu_status)
    local governor=$(echo "$cpu_status" | cut -d'|' -f1)
    local freq_mhz=$(echo "$cpu_status" | cut -d'|' -f2)
    local present_cores=$(echo "$cpu_status" | cut -d'|' -f3)
    local online_cores=$(echo "$cpu_status" | cut -d'|' -f4)
    local cpu_temp=$(echo "$cpu_status" | cut -d'|' -f5)

    echo ""
    echo -e "${BLUE}CPU Status:${NC}"
    echo -e "  Governor:     ${CYAN}${governor}${NC}"
    echo -e "  Frequency:    ${CYAN}${freq_mhz} MHz${NC}"
    echo -e "  Active cores: ${CYAN}${online_cores}/${present_cores}${NC}"
    echo -e "  Temperature:  ${CYAN}${cpu_temp}°C${NC}"

    # Check system health
    echo ""
    echo -e "${BLUE}System Health:${NC}"

    if has_battery_data "$csv_file"; then
        local battery_voltage=$(echo "$latest" | cut -d',' -f5)

        if (( $(echo "$battery_voltage < $BATTERY_CRITICAL" | bc -l) )); then
            echo -e "  Battery: ${RED}🔴 CRITICAL (<12.0V) - RECHARGE IMMEDIATELY${NC}"
        elif (( $(echo "$battery_voltage < $BATTERY_LOW" | bc -l) )); then
            echo -e "  Battery: ${RED}⚠ LOW (<12.4V) - Recharge recommended${NC}"
        elif (( $(echo "$battery_voltage < $BATTERY_GOOD" | bc -l) )); then
            echo -e "  Battery: ${YELLOW}⚠ MODERATE (12.4-13.2V) - Monitor level${NC}"
        else
            echo -e "  Battery: ${GREEN}✓ GOOD (>13.2V)${NC}"
        fi
    fi

    if (( $(echo "$supply_voltage < 4.75" | bc -l) )); then
        echo -e "  Supply:  ${RED}⚠ LOW - Check voltage regulator${NC}"
    elif (( $(echo "$supply_voltage < 4.9" | bc -l) )); then
        echo -e "  Supply:  ${YELLOW}⚠ MODERATE - Monitor 5V rail${NC}"
    else
        echo -e "  Supply:  ${GREEN}✓ GOOD${NC}"
    fi

    if (( $(echo "$power > 4.0" | bc -l) )); then
        echo -e "  Power:   ${YELLOW}⚠ HIGH - Check for active processes${NC}"
    else
        echo -e "  Power:   ${GREEN}✓ NORMAL${NC}"
    fi

    # CPU optimization status - check online cores, not present cores
    if [ "$governor" != "powersave" ] || [ "$online_cores" -gt 2 ]; then
        echo -e "  CPU:     ${YELLOW}⚠ NOT OPTIMIZED - See CPU optimization menu${NC}"
    else
        echo -e "  CPU:     ${GREEN}✓ OPTIMIZED (powersave, 2 cores)${NC}"
    fi
}

# Main menu
show_menu() {
    clear
    echo -e "${CYAN}"
    cat << "EOF"
╔═══════════════════════════════════════════════════════════════╗
║                                                               ║
║        Power Consumption Trend Analyzer v2.1                  ║
║        Pi Zero 2W + WittyPi + 4S LiFePO4 Battery             ║
║                                                               ║
╚═══════════════════════════════════════════════════════════════╝
EOF
    echo -e "${NC}"

    echo "Select analysis option:"
    echo ""
    echo "  1) Current Status"
    echo "  2) Battery Voltage Trends"
    echo "  3) Power Consumption Trends"
    echo "  4) Hourly Patterns (today)"
    echo "  5) Component Power Breakdown"
    echo "  6) Battery Runtime Estimation"
    echo "  7) CPU Power Optimization"
    echo "  8) Battery Health Check (NEW)"
    echo "  9) Full Report (all of the above)"
    echo " 10) Exit"
    echo ""
    echo -n "Enter choice [1-10]: "
}

# Main function
main() {
    # Check if data directory exists
    if [ ! -d "$DAILY_DATA_DIR" ]; then
        echo -e "${RED}Error: Data directory not found: $DAILY_DATA_DIR${NC}"
        exit 1
    fi

    # Check for required tools
    if ! command -v bc &> /dev/null; then
        echo -e "${YELLOW}Installing bc calculator...${NC}"
        sudo apt-get update && sudo apt-get install -y bc
    fi

    while true; do
        show_menu
        read -r choice

        case $choice in
            1)
                current_status
                ;;
            2)
                analyze_battery_trends
                ;;
            3)
                analyze_trends
                ;;
            4)
                analyze_hourly_patterns
                ;;
            5)
                component_breakdown
                ;;
            6)
                estimate_battery_runtime
                ;;
            7)
                cpu_power_optimization
                ;;
            8)
                battery_health_check
                ;;
            9)
                current_status
                analyze_battery_trends
                analyze_trends
                analyze_hourly_patterns
                component_breakdown
                estimate_battery_runtime
                cpu_power_optimization
                battery_health_check
                ;;
            10)
                echo -e "\n${GREEN}Goodbye!${NC}\n"
                exit 0
                ;;
            *)
                echo -e "\n${RED}Invalid option. Please try again.${NC}"
                ;;
        esac

        echo ""
        echo -e "${YELLOW}Press Enter to continue...${NC}"
        read -r
    done
}

# Run main function
main
