#!/bin/bash

BATTERY_XML="/tmp/battery.xml"
ioreg -a -r -c AppleSmartBattery > "$BATTERY_XML"

# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
YELLOW='\033[0;33m'
NC='\033[0m' # No color

# Helper function to extract key
read_xml() {
  local key="$1"
  xmllint --xpath "string(//key[.='$key']/following-sibling::*[1])" "$BATTERY_XML"
}

# Basic info
cycle_count=$(read_xml "CycleCount")
design_capacity=$(read_xml "DesignCapacity")
max_capacity=$(read_xml "AppleRawMaxCapacity")
current_capacity=$(read_xml "AppleRawCurrentCapacity")
voltage=$(read_xml "Voltage")
serial=$(read_xml "Serial")
temperature_raw=$(read_xml "Temperature")
temperature=$(echo "scale=1; $temperature_raw / 100" | bc)

# Health calculation
if [ "$design_capacity" -gt 0 ] && [ "$max_capacity" -gt 0 ]; then
  health=$(echo "scale=1; ($max_capacity / $design_capacity) * 100" | bc)
  health_str="(${health}% of Design Capacity)"
else
  health_str=""
fi

# Charge percentage
if [ "$max_capacity" -gt 0 ] && [ "$current_capacity" -gt 0 ]; then
  charge_percent=$(echo "scale=1; ($current_capacity / $max_capacity) * 100" | bc)
else
  charge_percent="N/A"
fi

# Cell voltages and imbalance
cell_voltages=($(xmllint --xpath "//key[.='CellVoltage']/following-sibling::array[1]/integer/text()" "$BATTERY_XML"))
cell_voltage_str=""
cell_min=${cell_voltages[0]}
cell_max=${cell_voltages[0]}

for v in "${cell_voltages[@]}"; do
  cell_voltage_str+=" $v mV"
  if [ "$v" -lt "$cell_min" ]; then cell_min=$v; fi
  if [ "$v" -gt "$cell_max" ]; then cell_max=$v; fi
done

imbalance=$((cell_max - cell_min))
if [ "$imbalance" -gt 100 ]; then
  imbalance_str="${RED}${imbalance} mV max imbalance${NC}"
else
  imbalance_str="${imbalance} mV max imbalance"
fi

# Lifetime data
max_discharge_current=$(read_xml "MaximumDischargeCurrent")
max_charge_current=$(read_xml "MaximumChargeCurrent")
max_pack_voltage=$(read_xml "MaximumPackVoltage")
min_pack_voltage=$(read_xml "MinimumPackVoltage")
max_temperature=$(read_xml "MaximumTemperature")
min_temperature=$(read_xml "MinimumTemperature")
max_temperature=$(echo "scale=1; $max_temperature / 10" | bc)
min_temperature=$(echo "scale=1; $min_temperature / 10" | bc)

# Current charge/discharge current

# Read charging current (in mA)
current_charge_current=$(xmllint --xpath "string(//key[.='ChargerData']/following-sibling::dict[1]/key[.='ChargingCurrent']/following-sibling::*[1])" "$BATTERY_XML")
# If values are empty, set to zero
charging_current=${charging_current:-0}
charging_voltage=${charging_voltage:-0}

echo -e "${CYAN}Battery Statistics:${NC}"
echo "---------------------------------"
echo -e "Cycle Count:          ${YELLOW}${cycle_count}${NC}"
echo -e "Design Capacity:      ${YELLOW}${design_capacity} mAh${NC}"
echo -e "Max Capacity:         ${YELLOW}${max_capacity} mAh ${health_str}${NC}"
echo -e "Current Capacity:     ${YELLOW}${current_capacity} mAh${NC}"
echo -e "Charge Percentage:    ${YELLOW}${charge_percent} %${NC}"


echo -e "Voltage:              ${YELLOW}${voltage} mV${NC}"
echo -e "Current Charging:     ${YELLOW}${current_charge_current} mA${NC}"
echo -e "Temperature:          ${YELLOW}${temperature} °C${NC}"
echo -e "Serial:               ${YELLOW}${serial}${NC}"

echo ""
echo -e "Cell Voltages:        ${YELLOW}${cell_voltage_str}${NC} (${imbalance_str})"

echo ""
echo -e "${CYAN}Lifetime Data:${NC}"
echo "---------------------------------"
echo -e "Max Discharge Current: ${YELLOW}${max_discharge_current} mA${NC}"
echo -e "Max Charge Current:    ${YELLOW}${max_charge_current} mA${NC}"
echo -e "Max Pack Voltage:      ${YELLOW}${max_pack_voltage} mV${NC}"
echo -e "Min Pack Voltage:      ${YELLOW}${min_pack_voltage} mV${NC}"
echo -e "Max Temperature:       ${YELLOW}${max_temperature} °C${NC}"
echo -e "Min Temperature:       ${YELLOW}${min_temperature} °C${NC}"

# Adapter details, only if connected
adapter_manufacturer=$(xmllint --xpath "string(//key[.='AdapterDetails']/following-sibling::dict[1]/key[.='Manufacturer']/following-sibling::*[1])" "$BATTERY_XML")
adapter_name=$(xmllint --xpath "string(//key[.='AdapterDetails']/following-sibling::dict[1]/key[.='Name']/following-sibling::*[1])" "$BATTERY_XML")

if [ -n "$adapter_manufacturer" ] && [ -n "$adapter_name" ]; then
  echo ""
  echo -e "${CYAN}Adapter Details:${NC}"
  echo "---------------------------------"
  echo -e "Manufacturer:         ${YELLOW}${adapter_manufacturer}${NC}"
  echo -e "Name:                 ${YELLOW}${adapter_name}${NC}"
fi